package com.yuncheng.spcyApi.spcyService;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.yuncheng.constant.SysUserConstant;
import com.yuncheng.entity.YcSysUser;
import com.yuncheng.vo.CurrentUserVo;
import com.yuncheng.vo.HttpResult;
import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuncheng.spcyApi.bo.*;
import com.yuncheng.spcyApi.constant.*;
import com.yuncheng.spcyApi.constant.common.BusinessConstant;
import com.yuncheng.spcyApi.constant.common.LogConstant;
import com.yuncheng.spcyApi.constant.common.SpcyCommonConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.constant.jcy.JcydjbConstant;
import com.yuncheng.spcyApi.entity.*;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.spcyApi.flow.SpcyFlowConstant;
import com.yuncheng.spcyApi.mapper.SpcyFlowMapper;
import com.yuncheng.spcyApi.mapper.SpcyRsHcyMapper;
import com.yuncheng.spcyApi.mapper.YcSysUserMapper;
import com.yuncheng.spcyApi.service.ISpcyLogService;
import com.yuncheng.spcyApi.service.ISpcyRsHcyService;
import com.yuncheng.spcyApi.service.IYcSysUserService;
import com.yuncheng.spcyApi.utils.*;
import com.yuncheng.spcyApi.vo.common.OperationLogVo;
import com.yuncheng.spcyApi.vo.common.OrderItemVo;
import com.yuncheng.spcyApi.vo.jcy.RsHcyVo;
import com.yuncheng.spcyApi.vo.spcy.SpcyFlowVo;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import utils.DateConversionUtils;
import utils.ExcelUtils;
import utils.LogUtils;
import utils.ObjectToMapUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.*;

@Component(value = "spcyJcyService")
public class SpcyJcyService {

    private static final Logger log = LoggerFactory.getLogger(SpcyJcyService.class);

    @Resource
    @Lazy
    private ISpcyRsHcyService spcyRsHcyService;

    @Resource
    @Lazy
    private SpcyRsHcyMapper spcyRsHcyMapper;

    @Resource
    @Lazy
    private YcSysUserMapper ycSysUserMapper;

    @Resource
    private IYcSysUserService sysUserService;

    @Resource
    @Lazy
    private SpcyFlowMapper spcyFlowMapper;

    @Resource
    private SpcyJcydjbService spcyJcydjbService;

    @Resource
    private BusinessConstant businessConstant;

    @Resource
    private MyExcelUtils myExcelUtils;

    @Resource
    private LocalFileUploadUtils localFileUploadUtils;

    @Resource
    private ISpcyLogService spcyLogService;

    /**
     * 检查员总库-分页列表查询
     * @param page
     * @param spcyRsHcy
     * @param orderItem 排序字段
     * @param orderType 排序升降序
     * @return
     */
    public HttpResult queryPageList(Page<RsHcyVo> page, RsHcyVo spcyRsHcy, String orderItem, String orderType){

        spcyRsHcy.setFywflcode(null);
        if (StringUtils.isBlank(spcyRsHcy.getFstate())) {
            spcyRsHcy.setFstate(SpcyCommonConstant.JCY_STATE_YX);
        }
        spcyRsHcy.setStatus(SysUserConstant.STATUS_YES); // 账户正常
        IPage<RsHcyVo> rsHcyListVoIPage = spcyRsHcyService.pageRsHcyList(page, spcyRsHcy,orderItem,orderType);
        return HttpResult.ok(rsHcyListVoIPage);
    }

    /**
     * 检查员账号管理 - 分页列表查询
     */
    public HttpResult pageJcyAccountList(Page<RsHcyVo> page, RsHcyVo user){
        IPage<RsHcyVo> pageList = spcyRsHcyMapper.pageJcyAccountList(page, user, SpcyConstant.HCY_USERTYPE_JCY, null);
        return HttpResult.ok(pageList);
    }

    /**
     * 检查员查询统计管理 - 分页列表查询
     */
    public HttpResult jcyCxtjPageList(Page<RsHcyVo> page, RsHcyVo user){
        IPage<RsHcyVo> pageList = spcyRsHcyMapper.jcyCxtjPageList(page, user, SpcyConstant.HCY_USERTYPE_JCY);

        List<RsHcyVo> records = pageList.getRecords();
        for (RsHcyVo jcy : records) {
            List<SpcyRsHcy> hcyList = spcyRsHcyService.selectJcyYxList(jcy.getId());
            String lx = "";
            for (int order = 0; order < hcyList.size(); order++) {
                if (StringUtils.isNotBlank(hcyList.get(order).getFlx())
                        && StringUtils.isNotBlank(lx)
                        && hcyList.get(order).getFlx().equals(JcydjbConstant.LB_YPZCSC)
                        && lx.contains(JcydjbConstant.LB_YPZCSC)) {
                } else {
                    lx += StringUtils.isNotBlank(lx) ? "/" + hcyList.get(order).getFlx() : hcyList.get(order).getFlx();
                }
            }
            jcy.setFlx(lx);
        }
        pageList.setRecords(records);

        return HttpResult.ok(pageList);
    }

    /**
     * 查询检查员所有待办列表 (现场检查)
     * @param onlyCurrentUser 查询当前用户待办
     */
    public HttpResult queryDbPage(Page<SpcyFlowVo> page, SpcyFlowVo spcyFlowVo, boolean onlyCurrentUser, OrderItemVo orderItemVo){
        CurrentUserVo user = GetCurrentUserUtils.getCurrentUser();
        if (user == null){
            return HttpResult.error("请重新登录，Token已失效！");
        }

        spcyFlowVo.setFblzt(SpcyConstant.BLZT_DB);
        spcyFlowVo.setFhjmc(SpcyFlowConstant.HJMC_XCJC);

        spcyFlowVo.setFlcmc(SpcyFlowConstant.LCMC_LIKE_SPCYLC);
        IPage<SpcyFlowVo> list = spcyFlowMapper.flowJobPage(page,onlyCurrentUser,user,spcyFlowVo, orderItemVo);
        return HttpResult.ok(list);
    }

    /**
     * 获取检查员管理-操作记录
     */
    public HttpResult queryJcyglLogRecord(Page<SpcyLog> page, OperationLogVo logVo){

        LambdaQueryWrapper<SpcyLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SpcyLog::getFhjmc, LogConstant.LOGS_JCYGL);
        queryWrapper.eq(StringUtils.isNotBlank(logVo.getId()), SpcyLog::getFpid, logVo.getId());
        queryWrapper.eq(StringUtils.isNotBlank(logVo.getFcontent()), SpcyLog::getFcontent, logVo.getFcontent());
        queryWrapper.eq(StringUtils.isNotBlank(logVo.getFczr()), SpcyLog::getFczr, logVo.getFczr());
        queryWrapper.eq(StringUtils.isNotBlank(logVo.getFczbm()), SpcyLog::getFczbm, logVo.getFczbm());
        queryWrapper.eq(StringUtils.isNotBlank(logVo.getFtype1()), SpcyLog::getFtype1, logVo.getFtype1());
        queryWrapper.eq(StringUtils.isNotBlank(logVo.getFtype2()), SpcyLog::getFtype2, logVo.getFtype2());

        if (logVo.getStartTime() != null){
            queryWrapper.ge(SpcyLog::getCreateTime, logVo.getStartTime());
        }
        if (logVo.getEndTime() != null){
            queryWrapper.le(SpcyLog::getCreateTime, logVo.getEndTime());
        }

        queryWrapper.orderByDesc(SpcyLog::getCreateTime);
        IPage<SpcyLog> pageList = spcyLogService.page(page, queryWrapper);


        return HttpResult.ok(pageList);
    }

    /**
     * 导入检查员
     */
    public HttpResult impJcyFileData(MultipartFile file){

        if (file.isEmpty()){
            return HttpResult.error("文件不存在");
        }

        //获取文件名
        String fileName = file.getOriginalFilename();

        //判断文件类型，这里我们只要xls文件
        if (fileName != null && !fileName.endsWith(".xls") && !fileName.endsWith(".xlsx")) {
            return HttpResult.error(1, "请选择“xls”或“xlsx”文件");
        }

        File fileUpload = localFileUploadUtils.uploadDempFile(file,fileName);

        // 获取导入的数据
        List<Map<String, Object>> mapsList = null;
        try {
            mapsList = myExcelUtils.paresExclToMapList(BusinessConstant.IMPORT_JCY_ACCOUNT_XML, fileUpload);
        } catch (Exception e) {
            log.error("导入检查员数据出错-{}",e.getMessage());
        }

        if (CollectionUtils.isNotEmpty(mapsList) && mapsList.size() > 0) {
            for (int order = 0; order < mapsList.size(); order++){
                ImportJcyBo importJcyBo = new ImportJcyBo();
                BeanUtil.copyProperties(mapsList.get(order),importJcyBo); // 将导入数据复制替换
//                BeanUtils.copyProperties(importJcyBo, map);
                this.initJcyAccount(importJcyBo, order, true);
            }
        }

        fileUpload.delete();

        return HttpResult.ok("导入成功");
    }

    /**
     * 初始化检查员 账号
     * @param order 序号
     * @param isImport 是否导入
     * */
    private void initJcyAccount(ImportJcyBo jcyBo,int order,boolean isImport){
        order++;
        String operationType = "新增检查员账户";
        if (isImport){
            operationType = "导入检查员账户";

            // 新增日志
            String addSysUserOper = operationType+"：";
            Map<String, Object> addUserMap = ObjectToMapUtils.objectToMap(jcyBo);
            addSysUserOper += LogUtils.MapToStringMethod(addUserMap);

            spcyLogService.addLogs(LogConstant.LOGS_JCYGL,addSysUserOper,null,operationType,SpcyConstant.LOGS_SYS_TYPE_TJ);
        }

        if (StringUtils.isBlank(jcyBo.getFsfzh())){
            StringBuffer msg = new StringBuffer("添加失败！");
            msg.append("第").append(order).append("条，");
            msg.append("身份证号为空！");
            throw new BusinessException(msg.toString());
        }

        if (StringUtils.isBlank(jcyBo.getRealname())){
            StringBuffer msg = new StringBuffer("添加失败！");
            msg.append("第").append(order).append("条，");
            msg.append("身份证号为[").append(jcyBo.getFsfzh()).append("]，");
            msg.append("姓名为空！");
            throw new BusinessException(msg.toString());
        }

        if (StringUtils.isBlank(jcyBo.getPhone())){
            StringBuffer msg = new StringBuffer("添加失败！");
            msg.append("第").append(order).append("条，");
            msg.append("身份证号为[").append(jcyBo.getFsfzh()).append("]，");
            msg.append("姓名为[").append(jcyBo.getRealname()).append("]，");
            msg.append("电话为空！");
            throw new BusinessException(msg.toString());
        }

        if (StringUtils.isBlank(jcyBo.getFjcylb())){
            StringBuffer msg = new StringBuffer("添加失败！");
            msg.append("第").append(order).append("条，");
            msg.append("身份证号为[").append(jcyBo.getFsfzh()).append("]，");
            msg.append("姓名为[").append(jcyBo.getRealname()).append("]，");
            msg.append("检查员类别为空！");
            throw new BusinessException(msg.toString());
        }

        if (StringUtils.isBlank(jcyBo.getFssk())){
            StringBuffer msg = new StringBuffer("添加失败！");
            msg.append("第").append(order).append("条");
            msg.append("身份证号为[").append(jcyBo.getFsfzh()).append("]，");
            msg.append("姓名为[").append(jcyBo.getRealname()).append("]，");
            msg.append("组长/组员为空！");
            throw new BusinessException(msg.toString());
        }else {
            if (!SpcyCommonConstant.JCY_SSK_LIST.contains(jcyBo.getFssk())){
                StringBuffer msg = new StringBuffer("添加失败！");
                msg.append("第").append(order).append("条");
                msg.append("身份证号为[").append(jcyBo.getFsfzh()).append("]，");
                msg.append("姓名为[").append(jcyBo.getRealname()).append("]，");
                msg.append("组长/组员/预备检查员内容不符合！格式为{组长/组员/预备检查员}");
                throw new BusinessException(msg.toString());
            }
        }

        // 验证该检查员类别是否存在
        String lb = StringPatternUtils.trimString(jcyBo.getFjcylb());
        if (!JcydjbConstant.DJB_JCY_LBS.contains(lb)){
            StringBuffer msg = new StringBuffer("添加失败！");
            msg.append("第").append(order).append("条");
            msg.append("身份证号为[").append(jcyBo.getFsfzh()).append("]，");
            msg.append("姓名为[").append(jcyBo.getRealname()).append("]，");
            msg.append("检查员类别[").append(jcyBo.getFjcylb()).append("]不符合！");
            throw new BusinessException(msg.toString());
        }

        // 新增用户账号
        YcSysUser newUser = new YcSysUser();
        String userId = "";

        // 根据检查员登记表获取基本信息
        Map djbMap = spcyJcydjbService.verifyIdCard(StringPatternUtils.trimString(jcyBo.getFsfzh()));
        boolean existSfzh = (Boolean) djbMap.get("flag");
        String jcydjbid = ""; // 检查员登记表id
        // 存在
        if (existSfzh) {
            SpcyRsJcydjb jcydjb = (SpcyRsJcydjb) djbMap.get("jcydjb");
            BeanUtil.copyProperties(jcydjb, newUser);
            jcydjbid = jcydjb.getId();
            newUser.setRealname(StringPatternUtils.trimString(jcydjb.getRealname()));
            newUser.setFsfzh(StringPatternUtils.trimString(jcydjb.getFsfzh()));
            newUser.setPhone(StringPatternUtils.trimString(jcydjb.getPhone()));

        }else {
            newUser.setRealname(StringPatternUtils.trimString(jcyBo.getRealname()));
            newUser.setPhone(StringPatternUtils.trimString(jcyBo.getPhone()));
            newUser.setFsfzh(StringPatternUtils.trimString(jcyBo.getFsfzh()));
        }

        /** 验证账号是否存在 */
        boolean isExistAccount = true;
        YcSysUser sfzUser = this.verifyUserIsExist(newUser.getFsfzh()); // 验证身份证号是否存在
        if (sfzUser == null){

            // 验证姓名为账户是否存在
            List<YcSysUser> realnameUser = this.verifyAccountIsExists(newUser.getRealname());
            if (CollectionUtil.isNotEmpty(realnameUser) && realnameUser.size() > 0){

                // 姓名+身份证号后四位
                String account = newUser.getRealname() + StringPatternUtils.subStringLastFourDigit(newUser.getFsfzh());
                List<YcSysUser> sfzNameUser = this.verifyAccountIsExists(account); // 验证姓名为账户是否存在

                if (CollectionUtil.isNotEmpty(sfzNameUser) && sfzNameUser.size() > 0){
                    StringBuffer msg = new StringBuffer("添加失败！");
                    msg.append("第").append(order).append("条");
                    msg.append("身份证号为[").append(newUser.getFsfzh()).append("]，");
                    msg.append("姓名为[").append(newUser.getRealname()).append("]，");
                    msg.append("账号已经存在！");
                    throw new BusinessException(msg.toString());

                }else {
                    isExistAccount = false;
                    newUser.setUsername(account); // 姓名当账号
                }
            }else {
                isExistAccount = false;
                newUser.setUsername(newUser.getRealname()); // 姓名当账号
            }
        }else {
            userId = sfzUser.getId();
        }

        if (!isExistAccount) {
            userId = GetUuIdUtils.ReplaceUuId();
            newUser.setId(userId);
            newUser.setPassword(SysUserConstant.PASSWORD); // 默认密码
            newUser.setSalt(SysUserConstant.SALT); // 加盐值
            newUser.setIsRealUser(SysUserConstant.IS_REAL_USER); // 真实用户
            newUser.setWorkNo(userId); // 工号
            newUser.setStatus(Integer.valueOf(SysUserConstant.STATUS)); // 有效状态
            newUser.setDelFlag(Integer.valueOf(SysUserConstant.DEL_FLAG)); // 删除-有效状态

            newUser.setOrgId(SpcyConstant.HCY_ORGID); // 部门编号
            newUser.setOrgName(SpcyConstant.HCY_ORGNAME); // 部门名称
            newUser.setOrgCode(SpcyConstant.HCY_ORGCODE); // 默认机构编码

            newUser.setCreateTime(new Date());
            newUser.setFgzzt(SpcyConstant.JCY_ZT_ZG);

            ycSysUserMapper.insert(newUser);

            // 更新检查员登记表账户状态
            spcyJcydjbService.updateZhzt(jcydjbid);

            // 同步登记表工作经历
            spcyJcydjbService.autoUserGzjl(jcydjbid,userId,newUser.getRealname());

            // 新增日志
            String addSysUserOper = operationType+"：";
            Map<String, Object> addUserMap = ObjectToMapUtils.objectToMap(newUser);
            addSysUserOper += LogUtils.MapToStringMethod(addUserMap);

            spcyLogService.addLogs(LogConstant.LOGS_JCYGL,addSysUserOper,userId,operationType,SpcyConstant.LOGS_SYS_TYPE_XZ);

            // 新增部门用户关系
            /*YcSysUserDepart ycSysUserDepart = new YcSysUserDepart();
            ycSysUserDepart.setId(GetUuIdUtils.ReplaceUuId());
            ycSysUserDepart.setUserId(userId);
            ycSysUserDepart.setDepId(SpcyConstant.HCY_ORGID); // 核查员部门编号
            ycSysUserDepart.setPositionId(""); // 职务编号
            ycSysUserDepart.setIsMajorDep(SysUserConstant.IS_MAJOR_DEP); // 是否主部门
            ycSysUserMapper.addYcSysUserDept(ycSysUserDepart);*/
            sysUserService.genJcyUserDeptGx(userId);

        }

        /** 验证改账号是否绑定改类别下的检查员 */
        boolean isExistJcy = spcyRsHcyService.verifyLbJcyIsExist(lb, userId);
        if (isExistJcy){
            // 存在
            // 更新对应类别检查员状态所属库
            spcyRsHcyService.updateJcyStateSsk(userId,lb,jcyBo.getFssk());

        }else {
            // 不存在
            String zytc = "";

            // 存在对应的检查员登记表信息
            if (existSfzh){
                String djbid = djbMap.get("id").toString();
                SpcyRsJcydjlb jcydjLb = this.getJcydjbLbByDjbId(djbid, lb, false);
                zytc = jcydjLb.getFjctz();
            }
            spcyRsHcyService.initNewLbJcy(userId, jcyBo.getFxllx(), lb, jcyBo.getFjcyxl(), jcyBo.getFssk(), zytc);
        }

        // 新增检查员角色-用户关系
        /*YcSysUserRole userRole = new YcSysUserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(SpcyCommonConstant.JCY_ROLE_ID);
        List<YcSysUserRole> userRoleList = ycSysUserMapper.getYcUserRole(userRole);
        if (CollectionUtil.isEmpty(userRoleList)) {
            userRole.setId(GetUuIdUtils.ReplaceUuId());
            ycSysUserMapper.addYcSysUserRole(userRole);
        }*/
        sysUserService.genJcyUserRoleGx(userId);

        // 新增检查员岗位-用户关系
        /*SysJobDto userGw = new SysJobDto();
        userGw.setId(SpcyCommonConstant.JCY_GW_ID);
        List<SysJobDto> userGwList = ycSysUserMapper.getUserGwByUserId(userGw, userId);
        if (CollectionUtil.isEmpty(userGwList)){
            ycSysUserMapper.addSysUserGw(GetUuIdUtils.ReplaceUuId(),userId,SpcyCommonConstant.JCY_GW_ID);
        }*/
        sysUserService.genJcyUserJobGx(userId);

    }

    /**
     * 验证用户是否存在
     * @param sfzh 身份证号
     */
    private YcSysUser verifyUserIsExist(String sfzh){
        // 身份证号是否存在
        List<YcSysUser> sfzUserList = ycSysUserMapper.selectList(new LambdaQueryWrapper<YcSysUser>()
                .eq(YcSysUser::getFsfzh, sfzh));

        if (CollectionUtil.isNotEmpty(sfzUserList)) {
            return sfzUserList.get(0);
        }

        return null;
    }

    /**
     * 验证用户是否存在
     * @param phone 手机号
     */
    private YcSysUser verifyUserIsExistByPhone(String phone){
        List<YcSysUser> sysUserList = sysUserService.selectUserByPhone(phone);
        if (CollectionUtil.isNotEmpty(sysUserList)) {
            return sysUserList.get(0);
        }

        return null;
    }

    /**
     * 验证身份证号是否存在
     * @param sfzh 身份证号
     */
    private void verifySfzhIsExist(String sfzh){

        // 身份证号是否存在
        List<YcSysUser> sfzUserList = sysUserService.selectUserBySfzh(sfzh);

        if (CollectionUtil.isNotEmpty(sfzUserList)) {
            throw new BusinessException("身份证号已经存在！无法添加新的账户！");
        }
    }

    /**
     * 验证账户是否存在
     * @param username 账号
     * @return
     */
    private List<YcSysUser> verifyAccountIsExists(String username){
        List<YcSysUser> accountUserList = sysUserService.selectUserByAccount(username);
        if (CollectionUtil.isNotEmpty(accountUserList)){
            return accountUserList;
        }else {
            return null;
        }
    }

    /**
     * 验证系统用户是否存在手机号
     * @param phone 手机号
     */
    private boolean verifyUserPhoneIsExist(String phone){
        List<YcSysUser> phoneList = sysUserService.selectUserByPhone(phone);
        if (CollectionUtil.isNotEmpty(phoneList)){
            return true;
        }

        return false;
    }

    /**
     * 获取检查员登记表中-选中的对应的专业特长
     */
    private SpcyRsJcydjlb getJcydjbLbByDjbId(String djbid, String jcylb){
        List<SpcyRsJcydjlb> lbList = spcyJcydjbService.queryJcyLbByDjbId(djbid, true);
        if (CollectionUtil.isNotEmpty(lbList)){
            for (int i=0; i<lbList.size(); i++){
                if (lbList.get(i).getFjcylb().equals(jcylb)){
                    return lbList.get(i);
                }
            }
        }

        return null;
    }

    /**
     * 获取检查员登记表中-对应的专业特长
     * @param isSfxz 是否选中
     */
    private SpcyRsJcydjlb getJcydjbLbByDjbId(String djbid, String jcylb, boolean isSfxz){
        List<SpcyRsJcydjlb> lbList = spcyJcydjbService.queryJcyLbByDjbId(djbid, isSfxz);
        if (CollectionUtil.isNotEmpty(lbList)){
            for (int i=0; i<lbList.size(); i++){
                if (lbList.get(i).getFjcylb().equals(jcylb)){
                    return lbList.get(i);
                }
            }
        }

        return null;
    }

    /**
     * 根据检查员id-获取对应的账户信息
     * @param id 检查员id
     */
    public SpcyRsHcy getUserInfoByJcyId(String id){
        SpcyRsHcy jcy = spcyRsHcyService.getById(id);

        return jcy;
    }

    /**
     * 更新检查员类型信息
     * @param buffer id 用户id
     */
    public void updateJcyInfo(HashMap<String,String> buffer){
        String id = buffer.get("id");
        if (StringUtils.isBlank(id)){
            throw new BusinessException("主要参数丢失，请联系管理员！");
        }
        SpcyRsHcy hcy = spcyRsHcyService.getById(id);
        if (hcy == null){
            throw new BusinessException("保存失败，对应检查员类别数据不存在！");
        }
        ConvertUtils.register(new DateConvert(), java.util.Date.class);
        Map<String, Object> map = ObjectToMapUtils.objectToMap(hcy);
        try {
            BeanUtils.populate(hcy,buffer);
        } catch (IllegalAccessException e) {
            log.error("更新核查员信息出错【IllegalAccessException】"+e.getMessage());
        } catch (InvocationTargetException e) {
            log.error("更新核查员信息出错【InvocationTargetException】"+e.getMessage());
        }
        spcyRsHcyService.updateById(hcy);

        String logNr = "修改检查员类别信息: ";
        logNr += LogUtils.BeanModifyMsg(hcy,map);

        spcyLogService.addLogs(LogConstant.LOGS_JCYGL,logNr,hcy.getFuserid(),"修改检查员类别信息",SpcyConstant.LOGS_SYS_TYPE_XG);
    }

    /**
     * 批量设置组长/组员
     * @param paramsBo ids/fssk
     */
    public void batchSzSsk(Map<String,String> paramsBo){
        String ids = paramsBo.get("ids");
        String fssk = paramsBo.get("fssk");

        if (StringUtils.isBlank(ids)){
            throw new BusinessException("请选择数据！");
        }
        if (StringUtils.isBlank(fssk)){
            throw new BusinessException("请选择设置组长/组员/预备检查员！");
        }

        List<String> idsList = StringPatternUtils.getListByIds(ids);

        for (int i=0; i<idsList.size(); i++) {
            RsHcyVo rsHcy = new RsHcyVo();
            rsHcy.setId(idsList.get(i));
            List<RsHcyVo> hcyList = spcyRsHcyMapper.getRsHcyList(rsHcy);

            LambdaUpdateWrapper<SpcyRsHcy> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(SpcyRsHcy::getId, idsList.get(i));

            SpcyRsHcy jcy = new SpcyRsHcy();
            jcy.setFssk(fssk);
            spcyRsHcyService.update(jcy, updateWrapper);

            StringBuffer msg = new StringBuffer("批量设置组长/组员-");
            if (CollectionUtil.isNotEmpty(hcyList)) {
                msg.append("姓名：[").append(hcyList.get(0).getRealname()).append("];");
                msg.append("检查员类别：[").append(hcyList.get(0).getFlx()).append("];");
                msg.append("将【原所属库]: [").append(hcyList.get(0).getFssk()).append("];");
            }
            msg.append("修改【所属库】为：[").append(fssk).append("];");
            spcyLogService.addLogs(LogConstant.LOGS_JCYGL,msg.toString(),hcyList.get(0).getFuserid(),"批量设置组长/组员",SpcyConstant.LOGS_SYS_TYPE_XG);

        }
    }

    /**
     * 批量设置检查员有效状态
     * @param paramsBo ids/fstate
     */
    public void batchSzJcyState(Map<String,String> paramsBo){
        String ids = paramsBo.get("ids");
        String fstate = paramsBo.get("fstate");

        if (StringUtils.isBlank(ids)){
            throw new BusinessException("请选择数据！");
        }

        if (StringUtils.isBlank(fstate)){
            throw new BusinessException("请选择设置有效状态！");
        }

        List<String> idsList = StringPatternUtils.getListByIds(ids);

        for (int i=0; i<idsList.size(); i++) {
            RsHcyVo rsHcy = new RsHcyVo();
            rsHcy.setId(idsList.get(i));
            List<RsHcyVo> hcyList = spcyRsHcyMapper.getRsHcyList(rsHcy);

            LambdaUpdateWrapper<SpcyRsHcy> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(SpcyRsHcy::getId, idsList.get(i));

            SpcyRsHcy jcy = new SpcyRsHcy();
            jcy.setFstate(fstate);
            spcyRsHcyService.update(jcy, updateWrapper);

            StringBuffer msg = new StringBuffer("批量设置检查员有效状态-");
            if (CollectionUtil.isNotEmpty(hcyList)) {
                msg.append("姓名：[").append(hcyList.get(0).getRealname()).append("];");
                msg.append("检查员类别：[").append(hcyList.get(0).getFlx()).append("];");
                msg.append("原有效状态: [").append(hcyList.get(0).getFstate()).append("];");
            }
            msg.append("修改有效状态为：[").append(fstate).append("];");
            spcyLogService.addLogs(LogConstant.LOGS_JCYGL,msg.toString(),hcyList.get(0).getFuserid(),"批量设置检查员有效状态",SpcyConstant.LOGS_SYS_TYPE_XG);
        }
    }

    /**
     * 查看账户检查员情况
     * @param id 用户id
     */
    public AddJcyParamBo seeAccount(String id){
        AddJcyParamBo paramBo = new AddJcyParamBo();
        AddJcyJbxxBo user = new AddJcyJbxxBo();
        List<AddJcylbBo> lbList = new ArrayList<>();

        // 所有类别
        String lbs = spcyJcydjbService.getSysConfigByCode(JcydjbConstant.SYS_CONFIG_LBS_CODE);
        List<String> allLbList = StringPatternUtils.getListByIds(lbs);

        if (StringUtils.isNotBlank(id)){
            RsHcyVo hcyVo = new RsHcyVo();
            hcyVo.setFuserid(id);
            List<RsHcyVo> jcyList = spcyRsHcyMapper.getRsHcyList(hcyVo);

            if (CollectionUtil.isNotEmpty(jcyList)){
                user.setId(jcyList.get(0).getFuserid());
                user.setFsfzh(jcyList.get(0).getFsfzh());

                // 该人员是否已解聘
                if (StringUtils.isNotBlank(jcyList.get(0).getFgzzt()) && jcyList.get(0).getFgzzt().equals(SpcyConstant.JCY_ZY_JP)){
                    user.setRealname(jcyList.get(0).getRealname() + "（已解聘）");
                }else {
                    user.setRealname(jcyList.get(0).getRealname());
                }

                user.setPhone(jcyList.get(0).getPhone());
            }

            for (int i=0; i < allLbList.size(); i++){
                String lb = allLbList.get(i);
                boolean isExistLb = false;

                for (int j=0; j<jcyList.size(); j++) {
                    // 相同类别
                    if (lb.equals(jcyList.get(j).getFlx())){
                        isExistLb = true;

                        AddJcylbBo jcylbBo = new AddJcylbBo();
                        jcylbBo.setLbid(jcyList.get(j).getId());
                        jcylbBo.setForder(i+1);

                        // 有效状态
                        if (StringUtils.isNotBlank(jcyList.get(j).getFstate()) && jcyList.get(j).getFstate().equals(SpcyCommonConstant.JCY_STATE_YX)) {
                            jcylbBo.setFxzzt("1");
                        }else {
                            jcylbBo.setFxzzt("0");
                        }

                        // 检查员类别是否等于检查员小类
                        if (StringUtils.isNotBlank(jcyList.get(j).getFjcyxl())) {
                            if (jcyList.get(j).getFlx().equals(jcyList.get(j).getFjcyxl())) {
                                jcylbBo.setLbmc(lb);
                            } else {
                                jcylbBo.setLbmc(lb + "（" + jcyList.get(j).getFjcyxl() + "）");
                            }
                        }else {
                            jcylbBo.setLbmc(lb);
                        }

                        jcylbBo.setFssk(jcyList.get(j).getFssk());

                        lbList.add(jcylbBo);
                    }
                }

                if (isExistLb){
                    continue;
                }

                AddJcylbBo jcylbBo = new AddJcylbBo();
                jcylbBo.setForder(i+1);
                jcylbBo.setFxzzt("0");
                jcylbBo.setLbmc(allLbList.get(i));

                lbList.add(jcylbBo);

            }

        }else {
            for (int i=0; i < allLbList.size(); i++){
                AddJcylbBo jcylbBo = new AddJcylbBo();
                jcylbBo.setForder(i+1);
                jcylbBo.setFxzzt("0");
                jcylbBo.setLbmc(allLbList.get(i));

                lbList.add(jcylbBo);
            }
        }

        paramBo.setUser(user);
        paramBo.setLbList(lbList);

        return paramBo;
    }

    /**
     * 新增账户
     */
    public String addAccount(AddJcyParamBo jcyParamBo){
        String userid = "";

        AddJcyJbxxBo user = jcyParamBo.getUser();



        if (StringUtils.isBlank(user.getId())){
            if (StringUtils.isBlank(user.getFsfzh())){
            throw new BusinessException("请填写身份证号！");
            }
            if (StringUtils.isBlank(user.getRealname())){
                throw new BusinessException("请填写姓名！");
            }
            if (StringUtils.isBlank(user.getPhone())){
                throw new BusinessException("请填写手机号！");
            }

            this.verifySfzhIsExist(StringPatternUtils.trimString(user.getFsfzh()));

            // 验证手机号是否被占用
            boolean isExistPhone = this.verifyUserPhoneIsExist(user.getPhone());
            if (isExistPhone){
                throw new BusinessException("手机号["+user.getPhone()+"]已经被占用了！");
            }
        }else {
            YcSysUser oldUser = sysUserService.getById(user.getId());
            if (oldUser != null) {

                if (StringUtils.isNotBlank(oldUser.getFsfzh())){
                    if (!oldUser.getFsfzh().equals(StringPatternUtils.trimString(user.getFsfzh()))) {
                        throw new BusinessException("身份证号不能修改！");
                    }
                }else {
                    this.verifySfzhIsExist(StringPatternUtils.trimString(user.getFsfzh()));
                }

                if (StringUtils.isNotBlank(oldUser.getPhone())){
                    if (!oldUser.getPhone().equals(StringPatternUtils.trimString(user.getPhone()))){
                        // 验证手机号是否被占用
                        boolean isExistPhone = this.verifyUserPhoneIsExist(user.getPhone());
                        if (isExistPhone){
                            throw new BusinessException("手机号["+user.getPhone()+"]已经被占用了！");
                        }
                    }
                }else {
                    // 验证手机号是否被占用
                    boolean isExistPhone = this.verifyUserPhoneIsExist(user.getPhone());
                    if (isExistPhone){
                        throw new BusinessException("手机号["+user.getPhone()+"]已经被占用了！");
                    }
                }

//                oldUser.setPhone(user.getPhone());
//                sysUserService.updateById(oldUser);
                userid = oldUser.getId();
            }else {
                throw new BusinessException("用户不存在！");
            }
        }

        List<AddJcylbBo> lbList = jcyParamBo.getLbList();
        boolean isSelectLb = false; // 新增的时候是否选中类别
        for (int j=0; j<lbList.size(); j++){
            ImportJcyBo jcyBo = new ImportJcyBo();

            if (StringUtils.isBlank(lbList.get(j).getLbid())) {
                if (lbList.get(j).getFxzzt().equals("1")) {
                    if (StringUtils.isBlank(lbList.get(j).getFssk())){
                        throw new BusinessException("请选择【"+lbList.get(j).getLbmc()+"】的组长/组员！");
                    }
                    jcyBo.setFjcylb(lbList.get(j).getLbmc());
                    jcyBo.setFssk(lbList.get(j).getFssk());

                    jcyBo.setFsfzh(user.getFsfzh());
                    jcyBo.setRealname(user.getRealname());
                    jcyBo.setPhone(user.getPhone());

                    jcyBo.setFjcyxl(JcydjbConstant.getJcyxlByJcyLb2(jcyBo.getFjcylb()));
                    jcyBo.setFxllx(SpcyConstant.getJcyXllxByJcylb(jcyBo.getFjcylb()));

                    spcyRsHcyService.initNewLbJcy(userid, jcyBo.getFxllx(), jcyBo.getFjcylb(), jcyBo.getFjcyxl(), jcyBo.getFssk(), "");

                    isSelectLb = true;
                }
            }else {
                isSelectLb = true;

                // 未选中
                if (lbList.get(j).getFxzzt().equals("0")){
                    this.stopJcyState(lbList.get(j), user);
                }else {

                    if (StringUtils.isBlank(lbList.get(j).getFssk())){
                        throw new BusinessException("请选择【"+lbList.get(j).getLbmc()+"】的组长/组员！");
                    }

                    // 选中
                    this.enableJcyState(lbList.get(j), user);
                }
            }
        }

        if (StringUtils.isBlank(user.getId()) && !isSelectLb){
            throw new BusinessException("请至少选择一个类别！");
        }

        /*YcSysUser sfzUser = this.verifyUserIsExist(user.getFsfzh()); // 验证身份证号是否存在
        if (sfzUser != null){
            userid = sfzUser.getId();
        }*/

        return userid;
    }

    /** 注销检查员 */
    private void stopJcyState(AddJcylbBo jcylbBo, AddJcyJbxxBo user){
        String jcyid = jcylbBo.getLbid();

        LambdaUpdateWrapper<SpcyRsHcy> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SpcyRsHcy::getId, jcyid);
        updateWrapper.eq(SpcyRsHcy::getFstate, SpcyCommonConstant.JCY_STATE_YX);

        SpcyRsHcy jcy = new SpcyRsHcy();
        jcy.setFstate(SpcyCommonConstant.JCY_STATE_ZX);
        spcyRsHcyService.update(jcy, updateWrapper);

        StringBuffer msg = new StringBuffer("注销检查员-");
        msg.append("类别：").append(jcylbBo.getLbmc());
        msg.append("姓名：").append(user.getRealname());
        spcyLogService.addLogs(LogConstant.LOGS_JCYGL,msg.toString(),user.getId(),"注销检查员",SpcyConstant.LOGS_SYS_TYPE_XG);

    }

    /** 恢复检查员 */
    private void enableJcyState(AddJcylbBo jcylbBo, AddJcyJbxxBo user){
        String jcyid = jcylbBo.getLbid();
        String ssk = jcylbBo.getFssk();

        this.updateJcyStateSsk(jcyid, ssk);

        StringBuffer msg = new StringBuffer("恢复检查员-");
        msg.append("类别：").append(jcylbBo.getLbmc());
        msg.append("姓名：").append(user.getRealname());
        msg.append("所属库: ").append(ssk);
        spcyLogService.addLogs(LogConstant.LOGS_JCYGL,msg.toString(),user.getId(),"恢复检查员",SpcyConstant.LOGS_SYS_TYPE_XG);
    }

    /**
     * 更新检查员状态所属库
     */
    private void updateJcyStateSsk(String jcyid,String ssk){
        LambdaUpdateWrapper<SpcyRsHcy> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SpcyRsHcy::getId, jcyid);

        SpcyRsHcy jcy = new SpcyRsHcy();
        jcy.setFstate(SpcyCommonConstant.JCY_STATE_YX);
        jcy.setFssk(ssk);
        spcyRsHcyService.update(jcy, updateWrapper);
    }

    /**
     * 更新检查员高频库状态
     * @param jcyid 检查原id
     * @param fgpk 高频库设置（是：改为 否； 否：改为 是）
     */
    public HttpResult updateJcyGpk(String jcyid,String fgpk){
        if (StringUtils.isBlank(jcyid)){
            return HttpResult.error("参数为空！");
        }
        if (StringUtils.isBlank(fgpk)){
            return HttpResult.error("高频库参数为空！");
        }

        SpcyRsHcy jcy = new SpcyRsHcy();
        if (fgpk.contains(SpcyConstant.JCY_GKP_NO)) {
            jcy.setFgpk(SpcyConstant.JCY_GKP_YES);

        }else if (fgpk.contains(SpcyConstant.JCY_GKP_YES)){
            jcy.setFgpk(SpcyConstant.JCY_GKP_NO);

        }else {
            return HttpResult.error("高频库参数不匹配！");
        }

        LambdaUpdateWrapper<SpcyRsHcy> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SpcyRsHcy::getId, jcyid);
        spcyRsHcyService.update(jcy, updateWrapper);

        return HttpResult.ok("操作成功");
    }

    /** 批量设置检查原高频库状态
     * @param fgpk 是/否
     * */
    public HttpResult batchSetJcyGpk(String jcyids, String fgpk){
        if (StringUtils.isBlank(jcyids)){
            return HttpResult.error("参数为空！");
        }

        SpcyRsHcy jcy = new SpcyRsHcy();
        jcy.setFgpk(fgpk);

        LambdaUpdateWrapper<SpcyRsHcy> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(SpcyRsHcy::getId, StringPatternUtils.getListByIds(jcyids));
        spcyRsHcyService.update(jcy, updateWrapper);

        return HttpResult.ok("操作成功");
    }

    /**
     * 停用账户
     * @param paramsBo
     */
    public void stopAccount(ParamsBo paramsBo){
        if (StringUtils.isBlank(paramsBo.getIds())){
            throw new BusinessException("请选择数据！");
        }

        List<String> idsList = StringPatternUtils.getListByIds(paramsBo.getIds());
        for (int i=0; i<idsList.size(); i++) {
            YcSysUser oldUser = sysUserService.getById(idsList.get(i));

            LambdaUpdateWrapper<YcSysUser> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(YcSysUser::getId, idsList.get(i));
            updateWrapper.eq(YcSysUser::getStatus, SysUserConstant.STATUS_YES);

            YcSysUser user = new YcSysUser();
            user.setStatus(SysUserConstant.STATUS_NO);
            sysUserService.update(user, updateWrapper);

            StringBuffer msg = new StringBuffer("停用检查员账户-");
            if (oldUser != null){
                msg.append("身份证号：[").append(oldUser.getFsfzh()).append("];");
                msg.append("姓名：[").append(oldUser.getRealname()).append("];");
                msg.append("手机号：[").append(oldUser.getPhone()).append("];");
            }
            spcyLogService.addLogs(LogConstant.LOGS_JCYGL,msg.toString(),idsList.get(i),"停用检查员账户",SpcyConstant.LOGS_SYS_TYPE_XG);
        }

    }

    /**
     * 恢复账户
     * @param paramsBo
     */
    public void enableAccount(ParamsBo paramsBo){
        if (StringUtils.isBlank(paramsBo.getIds())){
            throw new BusinessException("请选择数据！");
        }

        List<String> idsList = StringPatternUtils.getListByIds(paramsBo.getIds());
        for (int i=0; i<idsList.size(); i++) {
            YcSysUser oldUser = sysUserService.getById(idsList.get(i));

            LambdaUpdateWrapper<YcSysUser> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(YcSysUser::getId, idsList.get(i));
            updateWrapper.eq(YcSysUser::getStatus, 2);

            YcSysUser user = new YcSysUser();
            user.setStatus(SysUserConstant.STATUS_YES);

            sysUserService.update(user, updateWrapper);

            StringBuffer msg = new StringBuffer("恢复检查员账户-");
            if (oldUser != null){
                msg.append("身份证号：[").append(oldUser.getFsfzh()).append("];");
                msg.append("姓名：[").append(oldUser.getRealname()).append("];");
                msg.append("手机号：[").append(oldUser.getPhone()).append("];");
            }
            spcyLogService.addLogs(LogConstant.LOGS_JCYGL,msg.toString(),idsList.get(i),"恢复检查员账户",SpcyConstant.LOGS_SYS_TYPE_XG);

        }
    }

    /**
     * 账户重置密码
     * @param ids 用户ids
     */
    public void resetPwd(String ids){
        List<String> userIdList = StringPatternUtils.getListByIds(ids);

        List<YcSysUser> userList = sysUserService.listByIds(userIdList);
        if (CollectionUtil.isNotEmpty(userList)) {
            for (YcSysUser user : userList) {
                Map<String, Object> userMap = ObjectToMapUtils.objectToMap(user);

                user.setPassword(SysUserConstant.PASSWORD);
                user.setSalt(SysUserConstant.SALT);
                sysUserService.updateById(user);

                String lognr = "账户重置密码：";
                lognr += LogUtils.BeanModifyMsg(user, userMap);
                spcyLogService.addLogs(LogConstant.LOGS_JCYGL, lognr, user.getId(), "账户重置密码", SpcyConstant.LOGS_SYS_TYPE_XG);
            }
        }
    }

    /**
     * 下载检查员-导入模板
     */
    public void downJcyTemplate(HttpServletResponse response){
        try {
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode("downJcyTemplate.xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();
            myExcelUtils.buildImpModel(BusinessConstant.IMPORT_JCY_ACCOUNT_XML, out);
        } catch (Exception e) {
            log.error("下载检查员模板错误-{}",e.getMessage());
        }
    }

    /**
     * 导出检查员账户数据-表格excel
     */
    public void exportJcyData(RsHcyVo rsHcyVo, HttpServletResponse response){
        List<List<String>> resultList = new ArrayList<>();

        // 表头
        String[] titles = new String[]{"序号","账号","身份证号","姓名","手机号","检查员类别","组长/组员/预备检查员"};
        List<String> titleList = CollectionUtil.newArrayList(titles);
        resultList.add(titleList);

        List<YcSysUser> userList = this.getUserList(rsHcyVo);

        for (int i=0; i<userList.size(); i++){
            LambdaQueryWrapper<SpcyRsHcy> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SpcyRsHcy::getFuserid, userList.get(i).getId());
            queryWrapper.eq(SpcyRsHcy::getFusertype, SpcyConstant.HCY_USERTYPE_JCY);
            queryWrapper.isNotNull(SpcyRsHcy::getFlx);

            if (StringUtils.isNotBlank(rsHcyVo.getFlx())){
                queryWrapper.in(SpcyRsHcy::getFlx, StringPatternUtils.getListByIds(rsHcyVo.getFlx()));
            }
            if (StringUtils.isNotBlank(rsHcyVo.getFssk())){
                queryWrapper.like(SpcyRsHcy::getFssk, rsHcyVo.getFssk());
            }

            List<SpcyRsHcy> hcyList = spcyRsHcyService.list(queryWrapper);

            String lx = ""; // 检查员类别
            String ssk = ""; // 所属库
            for (int order=0; order<hcyList.size(); order++){
                lx += StringUtils.isNotBlank(lx) ? "/" + hcyList.get(order).getFlx() : hcyList.get(order).getFlx();

                String fssk = Optional.ofNullable(hcyList.get(order).getFssk()).orElseGet(() -> "无");
                ssk += StringUtils.isNotBlank(ssk) ? "/" + fssk : fssk;
            }

            // 数据
            List<String> dataList = new ArrayList<>();

            dataList.add(String.valueOf(i+1));
            dataList.add(userList.get(i).getUsername());
            dataList.add(userList.get(i).getFsfzh());

            dataList.add(userList.get(i).getRealname());
            dataList.add(userList.get(i).getPhone());
            dataList.add(lx);
            dataList.add(ssk);

            resultList.add(dataList);
        }

        // 相关检查员信息
        /*List<RsHcyVo> hcyList = spcyRsHcyMapper.getRsHcyList(rsHcyVo);
        for (int order = 0; order < hcyList.size(); order++){
            // 数据
            List<String> dataList = new ArrayList<>();

            dataList.add(String.valueOf(order+1));
            dataList.add(hcyList.get(order).getFsfzh());
            dataList.add(hcyList.get(order).getRealname());
            dataList.add(hcyList.get(order).getPhone());
            dataList.add(hcyList.get(order).getFlx());
            dataList.add(hcyList.get(order).getFssk());

            resultList.add(dataList);
        }*/

        // 文件名称
        String title = "检查员信息"+"("+ DateConversionUtils.DateToYear(new Date())+")";

        String rootUrl = localFileUploadUtils.getTempFileRootUrl();

        File outFile = ExcelUtils.getLocalDempXlsExcel(resultList, title, rootUrl);

        localFileUploadUtils.ejzLocalFileByZdyFile(outFile,response);
    }

    /**
     * 导出检查员账户数据-表格excel
     */
    public void exportJcyDataNew(RsHcyVo user, List<RsHcyVo> userList, HttpServletResponse response){
        List<List<String>> resultList = new ArrayList<>();

        // 表头
        String[] titles = new String[]{"序号","身份证号","姓名","性别","手机号","工作单位","单位部门","职称","专业","学历","单位类型","是否药检所","检查类型","检查身份"};
        List<String> titleList = CollectionUtil.newArrayList(titles);
        resultList.add(titleList);

        if (CollectionUtil.isEmpty(userList)) {
            userList = spcyRsHcyMapper.jcyCxtjList(user, SpcyConstant.HCY_USERTYPE_JCY);
        }

        for (int i=0; i<userList.size(); i++){
            List<SpcyRsHcy> hcyList = spcyRsHcyService.selectJcyYxList(userList.get(i).getId());

            String lx = ""; // 检查员类别
            String ssk = ""; // 所属库
            for (int order=0; order<hcyList.size(); order++){
                if (StringUtils.isNotBlank(hcyList.get(order).getFlx())
                        && StringUtils.isNotBlank(lx)
                        && hcyList.get(order).getFlx().equals(JcydjbConstant.LB_YPZCSC)
                        && lx.contains(JcydjbConstant.LB_YPZCSC)) {
                }else {
                    lx += StringUtils.isNotBlank(lx) ? "/" + hcyList.get(order).getFlx() : hcyList.get(order).getFlx();

                    String fssk = Optional.ofNullable(hcyList.get(order).getFssk()).orElseGet(() -> "无");
                    ssk += StringUtils.isNotBlank(ssk) ? "/" + fssk : fssk;
                }
            }

            // 数据
            List<String> dataList = new ArrayList<>();

            dataList.add(String.valueOf(i+1));

            dataList.add(userList.get(i).getFsfzh());
            dataList.add(userList.get(i).getRealname());
            String sex = "";
            if (userList.get(i).getSex() != null){
                if (userList.get(i).getSex().equals(1)){
                    sex = "男";
                }else if (userList.get(i).getSex().equals(2)){
                    sex = "女";
                }
            }
            dataList.add(sex);
            dataList.add(userList.get(i).getPhone());

            dataList.add(userList.get(i).getFgzdw());
            dataList.add(userList.get(i).getFgzdwbm());

            dataList.add(userList.get(i).getFzc());
            dataList.add(userList.get(i).getFsxzy());
            dataList.add(userList.get(i).getFxl());

            dataList.add(userList.get(i).getFdwlx());

            dataList.add(userList.get(i).getFsfyjsry());

            dataList.add(lx);
            dataList.add(ssk);

            resultList.add(dataList);
        }

        // 文件名称
        String title = "检查员信息"+"("+ DateConversionUtils.DateToYear(new Date())+")";

        ExcelUtils.getLocalTitleExcel(resultList,title,response);
    }

    /**
     * 导出检查员账户数据-表格excel
     */
    public void exportJcyData2(YcSysUser user, List<YcSysUser> userList, HttpServletResponse response){
        List<List<String>> resultList = new ArrayList<>();

        // 表头
        String[] titles = new String[]{"序号","身份证号","姓名","性别","手机号","工作单位","单位部门","工作单位地址","单位类型","是否药检所","所在地市","检查类型","检查身份"};
        List<String> titleList = CollectionUtil.newArrayList(titles);
        resultList.add(titleList);

        if (CollectionUtil.isEmpty(userList)) {
            userList = spcyRsHcyMapper.selectJcyUserList(user);
        }

        for (int i=0; i<userList.size(); i++){
            LambdaQueryWrapper<SpcyRsHcy> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SpcyRsHcy::getFuserid, userList.get(i).getId());
            queryWrapper.eq(SpcyRsHcy::getFusertype, SpcyConstant.HCY_USERTYPE_JCY);
            List<SpcyRsHcy> hcyList = spcyRsHcyService.list(queryWrapper);

            String lx = ""; // 检查员类别
            String ssk = ""; // 所属库
            for (int order=0; order<hcyList.size(); order++){
                if (StringUtils.isNotBlank(hcyList.get(order).getFlx())
                        && StringUtils.isNotBlank(lx)
                        && hcyList.get(order).getFlx().equals(JcydjbConstant.LB_YPZCSC)
                        && lx.contains(JcydjbConstant.LB_YPZCSC)) {
                }else {
                    lx += StringUtils.isNotBlank(lx) ? "/" + hcyList.get(order).getFlx() : hcyList.get(order).getFlx();

                    String fssk = Optional.ofNullable(hcyList.get(order).getFssk()).orElseGet(() -> "无");
                    ssk += StringUtils.isNotBlank(ssk) ? "/" + fssk : fssk;
                }
            }

            // 数据
            List<String> dataList = new ArrayList<>();

            dataList.add(String.valueOf(i+1));

            dataList.add(userList.get(i).getFsfzh());
            dataList.add(userList.get(i).getRealname());
            String sex = "";
            if (userList.get(i).getSex() != null){
                if (userList.get(i).getSex().equals(1)){
                    sex = "男";
                }else if (userList.get(i).getSex().equals(2)){
                    sex = "女";
                }
            }
            dataList.add(sex);
            dataList.add(userList.get(i).getPhone());

            dataList.add(userList.get(i).getFgzdw());
            dataList.add(userList.get(i).getFgzdwbm());
            dataList.add(userList.get(i).getFgzdwdz());
            dataList.add(userList.get(i).getFdwlx());

            dataList.add(userList.get(i).getFsfyjsry());
            dataList.add(userList.get(i).getFssqy());

            dataList.add(lx);
            dataList.add(ssk);

            resultList.add(dataList);
        }

        // 文件名称
        String title = "检查员信息"+"("+ DateConversionUtils.DateToYear(new Date())+")";

        ExcelUtils.getLocalTitleExcel(resultList,title,response);
    }

    /**
     * 导出检查员类别数据-表格excel
     */
    public void exportJcyLbData(RsHcyVo rsHcyVo, HttpServletResponse response){
        List<List<String>> resultList = new ArrayList<>();

        // 表头
        String[] titles = new String[]{"序号","身份证号","姓名","手机号","检查员类别","组长/组员/预备检查员"};
        List<String> titleList = CollectionUtil.newArrayList(titles);
        resultList.add(titleList);

        // 相关检查员信息
        List<RsHcyVo> hcyList = spcyRsHcyMapper.getRsHcyList(rsHcyVo);
        for (int order = 0; order < hcyList.size(); order++){
            // 数据
            List<String> dataList = new ArrayList<>();

            dataList.add(String.valueOf(order+1));
            dataList.add(hcyList.get(order).getFsfzh());
            dataList.add(hcyList.get(order).getRealname());
            dataList.add(hcyList.get(order).getPhone());
            dataList.add(hcyList.get(order).getFlx());
            dataList.add(hcyList.get(order).getFssk());

            resultList.add(dataList);
        }

        // 文件名称
        String title = "检查员信息"+"("+ DateConversionUtils.DateToYear(new Date())+")";

        String rootUrl = localFileUploadUtils.getTempFileRootUrl();

        File outFile = ExcelUtils.getLocalDempXlsExcel(resultList, title, rootUrl);

        localFileUploadUtils.ejzLocalFileByZdyFile(outFile,response);
    }

    /**
     * 查询检查员库对应的人员信息列表
     * @param rsHcyVo
     * @return
     */
    private List<YcSysUser> getUserList(RsHcyVo rsHcyVo){
        List<YcSysUser> userList = new ArrayList<>();
        if (StringUtils.isNotBlank(rsHcyVo.getUserids())){
            userList = sysUserService.listByIds(StringPatternUtils.getListByIds(rsHcyVo.getUserids()));
        }else {
            LambdaQueryWrapper<YcSysUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.like(StringUtils.isNotBlank(rsHcyVo.getUsername()),YcSysUser::getUsername, rsHcyVo.getUsername());
            queryWrapper.like(StringUtils.isNotBlank(rsHcyVo.getRealname()),YcSysUser::getRealname, rsHcyVo.getRealname());
            queryWrapper.like(StringUtils.isNotBlank(rsHcyVo.getFsfzh()),YcSysUser::getFsfzh, rsHcyVo.getFsfzh());
            queryWrapper.like(StringUtils.isNotBlank(rsHcyVo.getPhone()),YcSysUser::getPhone, rsHcyVo.getPhone());
            queryWrapper.like(StringUtils.isNotBlank(rsHcyVo.getEmail()),YcSysUser::getEmail, rsHcyVo.getEmail());
            queryWrapper.like(StringUtils.isNotBlank(rsHcyVo.getFgzdw()),YcSysUser::getFgzdw, rsHcyVo.getFgzdw());
            queryWrapper.like(StringUtils.isNotBlank(rsHcyVo.getFgzzt()),YcSysUser::getFgzzt, rsHcyVo.getFgzzt());
            queryWrapper.like(StringUtils.isNotBlank(rsHcyVo.getFgzdwdz()),YcSysUser::getFgzdwdz, rsHcyVo.getFgzdwdz());
            queryWrapper.like(StringUtils.isNotBlank(rsHcyVo.getFxl()),YcSysUser::getFxl, rsHcyVo.getFxl());

            if (rsHcyVo.getStatus() != null) {
                queryWrapper.eq(YcSysUser::getStatus, rsHcyVo.getStatus());
            }

            if (rsHcyVo.getSex() != null) {
                queryWrapper.eq(YcSysUser::getSex, rsHcyVo.getSex());
            }

            queryWrapper.orderByDesc(YcSysUser::getCreateTime);
            sysUserService.list(queryWrapper);
        }

        return userList;
    }


    /**
     * 导入检查员
     */
    public void initUploadJcyData(MultipartFile file, String fxllx, String fjcylb, String fjcyxl, HttpServletResponse response){

        if (file.isEmpty()){
//            return HttpResult.error("文件不存在");
        }

        //获取文件名
        String fileName = file.getOriginalFilename();

        //判断文件类型，这里我们只要xls文件
        if (fileName != null && !fileName.endsWith(".xls") && !fileName.endsWith(".xlsx")) {
//            return HttpResult.error(1, "请选择“xls”或“xlsx”文件");
        }

        File fileUpload = localFileUploadUtils.uploadDempFile(file,fileName);

        // 获取导入的数据
        List<Map<String, Object>> mapsList = null;
        try {
            mapsList = myExcelUtils.paresExclToMapList(BusinessConstant.IMPORT_JCY_ACCOUNT_XML, fileUpload);
        } catch (Exception e) {
            log.error("导入检查员数据出错-{}",e.getMessage());
        }

        List<List<String>> msgList = new ArrayList<>();
        msgList.add(CollectionUtil.newArrayList("手机号","采集表是否存在","采集数量","用户表存在","用户数量"));

        if (CollectionUtils.isNotEmpty(mapsList) && mapsList.size() > 0) {
            for (int order = 0; order < mapsList.size(); order++){
                ImportJcyBo importJcyBo = new ImportJcyBo();
                BeanUtil.copyProperties(mapsList.get(order),importJcyBo); // 将导入数据复制替换
                importJcyBo.setFjcylb(fjcylb);
                importJcyBo.setFxllx(fxllx);
                importJcyBo.setFjcyxl(fjcyxl);
                msgList.add(initUploadJcyDataTest(importJcyBo, order, true));
            }
        }

        // 文件名称
        String title = "数据对比";
        ExcelUtils.getLocalTitleExcel(msgList,title,response);
    }

    /**
     * 初始化检查员数据-20231227
     * @param jcyBo
     * @param order
     * @param isImport
     */
    private List<String> initUploadJcyDataTest(ImportJcyBo jcyBo,int order,boolean isImport){

        order++;
//        String operationType = "新增检查员账户";
        if (isImport){
            /*operationType = "导入检查员账户";

            // 新增日志
            String addSysUserOper = operationType+"：";
            Map<String, Object> addUserMap = ObjectToMapUtils.objectToMap(jcyBo);
            addSysUserOper += LogUtils.MapToStringMethod(addUserMap);

            spcyLogService.addLogs(LogConstant.LOGS_JCYGL,addSysUserOper,null,operationType,SpcyConstant.LOGS_SYS_TYPE_TJ);*/
        }

        if (StringUtils.isBlank(jcyBo.getRealname())){
            StringBuffer msg = new StringBuffer("添加失败！");
            msg.append("第").append(order).append("条，");
            msg.append("姓名为空！");
            throw new BusinessException(msg.toString());
        }

        if (StringUtils.isBlank(jcyBo.getPhone())){
            StringBuffer msg = new StringBuffer("添加失败！");
            msg.append("第").append(order).append("条，");
            msg.append("姓名为[").append(jcyBo.getRealname()).append("]，");
            msg.append("电话为空！");
            throw new BusinessException(msg.toString());
        }

        if (StringUtils.isBlank(jcyBo.getFjcylb())){
            StringBuffer msg = new StringBuffer("添加失败！");
            msg.append("第").append(order).append("条，");
            msg.append("姓名为[").append(jcyBo.getRealname()).append("]，");
            msg.append("检查员类别为空！");
            throw new BusinessException(msg.toString());
        }

        if (StringUtils.isBlank(jcyBo.getFssk())){
            StringBuffer msg = new StringBuffer("添加失败！");
            msg.append("第").append(order).append("条");
            msg.append("姓名为[").append(jcyBo.getRealname()).append("]，");
            msg.append("组长/组员为空！");
            throw new BusinessException(msg.toString());
        }else {
            if (!SpcyCommonConstant.JCY_SSK_LIST.contains(jcyBo.getFssk())){
                StringBuffer msg = new StringBuffer("添加失败！");
                msg.append("第").append(order).append("条");
                msg.append("姓名为[").append(jcyBo.getRealname()).append("]，");
                msg.append("组长/组员/预备检查员内容不符合！格式为{组长/组员/预备检查员}");
                throw new BusinessException(msg.toString());
            }
        }

        // 验证该检查员类别是否存在
        String lb = StringPatternUtils.trimString(jcyBo.getFjcylb());
        if (!JcydjbConstant.DJB_JCY_LBS.contains(lb)){
            StringBuffer msg = new StringBuffer("添加失败！");
            msg.append("第").append(order).append("条");
            msg.append("姓名为[").append(jcyBo.getRealname()).append("]，");
            msg.append("检查员类别[").append(jcyBo.getFjcylb()).append("]不符合！");
            throw new BusinessException(msg.toString());
        }

        // 新增用户账号
        YcSysUser newUser = new YcSysUser();
        String userId = "";

        String msg_phone = "";
        String msg_cjcz = "不存在";
        String msg_cjsl = "0";
        String msg_usercz = "不存在";
        String msg_usersl = "0";

        msg_phone = StringPatternUtils.trimString(jcyBo.getPhone());

        // 根据检查员登记表获取基本信息
        Map djbMap = spcyJcydjbService.verifyPhone(StringPatternUtils.trimString(msg_phone));
        boolean existSfzh = (Boolean) djbMap.get("flag");
        String jcydjbid = ""; // 检查员登记表id
        // 存在
        if (existSfzh) {
            SpcyRsJcydjb jcydjb = (SpcyRsJcydjb) djbMap.get("jcydjb");
            BeanUtil.copyProperties(jcydjb, newUser);
            jcydjbid = jcydjb.getId();

            newUser.setRealname(StringPatternUtils.trimString(jcydjb.getRealname()));
            newUser.setFsfzh(StringPatternUtils.trimString(jcydjb.getFsfzh()));
            newUser.setPhone(jcydjb.getPhone());

            newUser.setFgzdw(jcydjb.getFdwqc());
            newUser.setFgzdwbm(jcydjb.getFdwbm());
            newUser.setFdwlx(jcydjb.getFdwlx());
            newUser.setFgznx(jcydjb.getFdwgznx());
            newUser.setFcsjckssj(jcydjb.getFcsjckssj());

            newUser.setFgzdwdz(jcydjb.getFdwdz());
            newUser.setFsftxyp(jcydjb.getFsftxyp());
            newUser.setFsfyjsry(jcydjb.getFsfyjs());

            newUser.setUserQq(jcydjb.getFqqhm());
            newUser.setFssqy(jcydjb.getFssds());

            msg_cjcz = "存在";
            msg_cjsl = "1";
        }else {
            newUser.setRealname(StringPatternUtils.trimString(jcyBo.getRealname()));
            newUser.setPhone(msg_phone);
            newUser.setFsfzh(StringPatternUtils.trimString(jcyBo.getFsfzh()));

        }

        /** 验证账号是否存在 */
        boolean isExistAccount = true;
        YcSysUser sfzUser = null;
        int userCount = 0; // 用户数量
        String newAccount = ""; // 账号

        // 手机号查询用户是否存在
        List<YcSysUser> userList = sysUserService.selectUserByPhone(newUser.getPhone());
        if (CollectionUtil.isNotEmpty(userList)){
            if (userList.size() == 1){
                sfzUser = userList.get(0);
            }
            userCount = userList.size();
            msg_cjcz = "存在";
            msg_cjsl = String.valueOf(userCount);
        }

        if (userCount == 0){

            // 验证姓名为账户是否存在
            List<YcSysUser> realnameUser = this.verifyAccountIsExists(newUser.getRealname());
            if (CollectionUtil.isNotEmpty(realnameUser) && realnameUser.size() > 0){

                // 姓名+身份证号后四位
                String account = newUser.getRealname() + StringPatternUtils.subStringLastFourDigit(newUser.getFsfzh());
                List<YcSysUser> sfzNameUser = this.verifyAccountIsExists(account); // 验证姓名为账户是否存在

                if (CollectionUtil.isNotEmpty(sfzNameUser) && sfzNameUser.size() > 0){
                    StringBuffer msg = new StringBuffer("添加失败！");
                    msg.append("第").append(order).append("条");
                    msg.append("姓名为[").append(newUser.getRealname()).append("]，");
                    msg.append("账号已经存在！");
                    throw new BusinessException(msg.toString());

                }else {
                    isExistAccount = false;
                    newAccount = account; // 姓名+身份证后四位=账号
                }
            }else {
                isExistAccount = false;
                newAccount = newUser.getRealname(); // 姓名=账号
            }
        }

        if (userCount == 1){
            userId = sfzUser.getId();
        }

        if (!isExistAccount) {
            userId = GetUuIdUtils.ReplaceUuId();
            newUser.setId(userId);
            newUser.setUsername(newAccount);
            newUser.setPassword(SysUserConstant.PASSWORD); // 默认密码
            newUser.setSalt(SysUserConstant.SALT); // 加盐值
            newUser.setIsRealUser(SysUserConstant.IS_REAL_USER); // 真实用户
            newUser.setWorkNo(userId); // 工号
            newUser.setStatus(Integer.valueOf(SysUserConstant.STATUS)); // 有效状态
            newUser.setDelFlag(Integer.valueOf(SysUserConstant.DEL_FLAG)); // 删除-有效状态

            newUser.setOrgId(SpcyConstant.HCY_ORGID); // 部门编号
            newUser.setOrgName(SpcyConstant.HCY_ORGNAME); // 部门名称
            newUser.setOrgCode(SpcyConstant.HCY_ORGCODE); // 默认机构编码

            newUser.setCreateTime(new Date());
            newUser.setFgzzt(SpcyConstant.JCY_ZT_ZG);

            ycSysUserMapper.insert(newUser);

            // 更新检查员登记表账户状态
            spcyJcydjbService.updateZhzt(jcydjbid);

            // 同步登记表工作经历
            spcyJcydjbService.autoUserGzjl(jcydjbid,userId,newUser.getRealname());

            // 同步登记表发表文章
            spcyJcydjbService.autoUserFbwz(jcydjbid,userId);

            // 新增部门用户关系
            /*YcSysUserDepart ycSysUserDepart = new YcSysUserDepart();
            ycSysUserDepart.setId(GetUuIdUtils.ReplaceUuId());
            ycSysUserDepart.setUserId(userId);
            ycSysUserDepart.setDepId(SpcyConstant.HCY_ORGID); // 核查员部门编号
            ycSysUserDepart.setPositionId(""); // 职务编号
            ycSysUserDepart.setIsMajorDep(SysUserConstant.IS_MAJOR_DEP); // 是否主部门
            ycSysUserMapper.addYcSysUserDept(ycSysUserDepart);*/

            sysUserService.genJcyUserDeptGx(userId);

        }

        /** 验证改账号是否绑定改类别下的检查员 */
        boolean isExistJcy = spcyRsHcyService.verifyLbJcyIsExist(lb, jcyBo.getFjcyxl(),userId);
        if (isExistJcy){
            // 存在
            // 更新对应类别检查员状态所属库
            spcyRsHcyService.updateJcyStateSsk(userId,lb,jcyBo.getFjcyxl(),jcyBo.getFssk());

        }else {
            // 不存在
            String zytc = "";

            // 存在对应的检查员登记表信息
            if (existSfzh){
                SpcyRsJcydjlb jcydjLb = this.getJcydjbLbByDjbId(jcydjbid, lb, false);
                zytc = jcydjLb.getFjctz();
            }
            spcyRsHcyService.initNewLbJcy(userId, jcyBo.getFxllx(), lb, jcyBo.getFjcyxl(), jcyBo.getFssk(), zytc);
        }

        // 新增检查员角色-用户关系
        /*YcSysUserRole userRole = new YcSysUserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(SpcyCommonConstant.JCY_ROLE_ID);
        List<YcSysUserRole> userRoleList = ycSysUserMapper.getYcUserRole(userRole);
        if (CollectionUtil.isEmpty(userRoleList)) {
            userRole.setId(GetUuIdUtils.ReplaceUuId());
            ycSysUserMapper.addYcSysUserRole(userRole);
        }*/
        sysUserService.genJcyUserRoleGx(userId);

        // 新增检查员岗位-用户关系
        /*SysJobDto userGw = new SysJobDto();
        userGw.setId(SpcyCommonConstant.JCY_GW_ID);
        List<SysJobDto> userGwList = ycSysUserMapper.getUserGwByUserId(userGw, userId);
        if (CollectionUtil.isEmpty(userGwList)){
            ycSysUserMapper.addSysUserGw(GetUuIdUtils.ReplaceUuId(),userId,SpcyCommonConstant.JCY_GW_ID);
        }*/
        sysUserService.genJcyUserJobGx(userId);

        return CollectionUtil.newArrayList(msg_phone,msg_cjcz,msg_cjsl,msg_usercz,msg_usersl);
    }

    /**
     * 初始化检查员数据-20231227
     * @param jcyBo
     * @param order
     * @param isImport
     */
    private List<String> initUploadJcyDataTest2(ImportJcyBo jcyBo,int order,boolean isImport){

        order++;

        String lb = StringPatternUtils.trimString(jcyBo.getFjcylb());

        // 新增用户账号
        YcSysUser newUser = new YcSysUser();
        String userId = "";

        String msg_SFZH = "";
        String msg_cjcz = "不存在";
        String msg_cjsl = "0";
        String msg_usercz = "不存在";
        String msg_usersl = "0";

        msg_SFZH = StringPatternUtils.trimString(jcyBo.getFsfzh());

        // 根据检查员登记表获取基本信息
        Map djbMap = spcyJcydjbService.verifyIdCard(StringPatternUtils.trimString(msg_SFZH));
        boolean existSfzh = (Boolean) djbMap.get("flag");
        String jcydjbid = ""; // 检查员登记表id
        // 存在
        if (existSfzh) {
            SpcyRsJcydjb jcydjb = (SpcyRsJcydjb) djbMap.get("jcydjb");
            BeanUtil.copyProperties(jcydjb, newUser);
            jcydjbid = jcydjb.getId();

            newUser.setRealname(StringPatternUtils.trimString(jcydjb.getRealname()));
            newUser.setFsfzh(StringPatternUtils.trimString(jcydjb.getFsfzh()));
            newUser.setPhone(jcydjb.getPhone());

            newUser.setFgzdw(jcydjb.getFdwqc());
            newUser.setFgzdwbm(jcydjb.getFdwbm());
            newUser.setFdwlx(jcydjb.getFdwlx());
            newUser.setFgznx(jcydjb.getFdwgznx());
            newUser.setFcsjckssj(jcydjb.getFcsjckssj());

            newUser.setFgzdwdz(jcydjb.getFdwdz());
            newUser.setFsftxyp(jcydjb.getFsftxyp());
            newUser.setFsfyjsry(jcydjb.getFsfyjs());

            newUser.setUserQq(jcydjb.getFqqhm());
            newUser.setFssqy(jcydjb.getFssds());

            msg_cjcz = "存在";
            msg_cjsl = "1";
        }else {
            newUser.setRealname(StringPatternUtils.trimString(jcyBo.getRealname()));
            newUser.setPhone("");
            newUser.setFsfzh(StringPatternUtils.trimString(jcyBo.getFsfzh()));

        }

        /** 验证账号是否存在 */
        boolean isExistAccount = true;
        YcSysUser sfzUser = null;
        int userCount = 0; // 用户数量
        String newAccount = ""; // 账号

        // 手机号查询用户是否存在
//        List<YcSysUser> userList = sysUserService.selectUserByPhone(newUser.getPhone());
        List<YcSysUser> userList = sysUserService.selectUserBySfzh(newUser.getFsfzh());
        if (CollectionUtil.isNotEmpty(userList)){
            if (userList.size() == 1){
                sfzUser = userList.get(0);
            }
            userCount = userList.size();
            msg_cjcz = "存在";
            msg_cjsl = String.valueOf(userCount);
        }

        if (userCount == 0){

            // 验证姓名为账户是否存在
            List<YcSysUser> realnameUser = this.verifyAccountIsExists(newUser.getRealname());
            if (CollectionUtil.isNotEmpty(realnameUser) && realnameUser.size() > 0){

                // 姓名+身份证号后四位
                String account = newUser.getRealname() + StringPatternUtils.subStringLastFourDigit(newUser.getFsfzh());
                List<YcSysUser> sfzNameUser = this.verifyAccountIsExists(account); // 验证姓名为账户是否存在

                if (CollectionUtil.isNotEmpty(sfzNameUser) && sfzNameUser.size() > 0){
                    StringBuffer msg = new StringBuffer("添加失败！");
                    msg.append("第").append(order).append("条");
                    msg.append("姓名为[").append(newUser.getRealname()).append("]，");
                    msg.append("账号已经存在！");
                    throw new BusinessException(msg.toString());

                }else {
                    isExistAccount = false;
                    newAccount = account; // 姓名+身份证后四位=账号
                }
            }else {
                isExistAccount = false;
                newAccount = newUser.getRealname(); // 姓名=账号
            }
        }

        if (userCount == 1){
            userId = sfzUser.getId();
        }

        if (!isExistAccount) {
            userId = GetUuIdUtils.ReplaceUuId();
            newUser.setId(userId);
            newUser.setUsername(newAccount);
            newUser.setPassword(SysUserConstant.PASSWORD); // 默认密码
            newUser.setSalt(SysUserConstant.SALT); // 加盐值
            newUser.setIsRealUser(SysUserConstant.IS_REAL_USER); // 真实用户
            newUser.setWorkNo(userId); // 工号
            newUser.setStatus(Integer.valueOf(SysUserConstant.STATUS)); // 有效状态
            newUser.setDelFlag(Integer.valueOf(SysUserConstant.DEL_FLAG)); // 删除-有效状态

            newUser.setOrgId(SpcyConstant.HCY_ORGID); // 部门编号
            newUser.setOrgName(SpcyConstant.HCY_ORGNAME); // 部门名称
            newUser.setOrgCode(SpcyConstant.HCY_ORGCODE); // 默认机构编码

            newUser.setCreateTime(new Date());
            newUser.setFgzzt(SpcyConstant.JCY_ZT_ZG);

            ycSysUserMapper.insert(newUser);

            // 更新检查员登记表账户状态
            spcyJcydjbService.updateZhzt(jcydjbid);

            // 同步登记表工作经历
            spcyJcydjbService.autoUserGzjl(jcydjbid,userId,newUser.getRealname());

            // 同步登记表发表文章
            spcyJcydjbService.autoUserFbwz(jcydjbid,userId);

            // 新增部门用户关系
            /*YcSysUserDepart ycSysUserDepart = new YcSysUserDepart();
            ycSysUserDepart.setId(GetUuIdUtils.ReplaceUuId());
            ycSysUserDepart.setUserId(userId);
            ycSysUserDepart.setDepId(SpcyConstant.HCY_ORGID); // 核查员部门编号
            ycSysUserDepart.setPositionId(""); // 职务编号
            ycSysUserDepart.setIsMajorDep(SysUserConstant.IS_MAJOR_DEP); // 是否主部门
            ycSysUserMapper.addYcSysUserDept(ycSysUserDepart);*/

            sysUserService.genJcyUserDeptGx(userId);

        }

        /** 验证改账号是否绑定改类别下的检查员 */
        boolean isExistJcy = spcyRsHcyService.verifyLbJcyIsExist(lb, jcyBo.getFjcyxl(),userId);
        if (isExistJcy){
            // 存在
            // 更新对应类别检查员状态所属库
            spcyRsHcyService.updateJcyStateSsk(userId,lb,jcyBo.getFjcyxl(),jcyBo.getFssk());

        }else {
            // 不存在
            String zytc = "";

            // 存在对应的检查员登记表信息
            if (existSfzh){
                SpcyRsJcydjlb jcydjLb = this.getJcydjbLbByDjbId(jcydjbid, lb, false);
                zytc = jcydjLb.getFjctz();
            }
            spcyRsHcyService.initNewLbJcy(userId, jcyBo.getFxllx(), lb, jcyBo.getFjcyxl(), jcyBo.getFssk(), zytc);
        }

        // 新增检查员角色-用户关系
        /*YcSysUserRole userRole = new YcSysUserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(SpcyCommonConstant.JCY_ROLE_ID);
        List<YcSysUserRole> userRoleList = ycSysUserMapper.getYcUserRole(userRole);
        if (CollectionUtil.isEmpty(userRoleList)) {
            userRole.setId(GetUuIdUtils.ReplaceUuId());
            ycSysUserMapper.addYcSysUserRole(userRole);
        }*/
        sysUserService.genJcyUserRoleGx(userId);

        // 新增检查员岗位-用户关系
        /*SysJobDto userGw = new SysJobDto();
        userGw.setId(SpcyCommonConstant.JCY_GW_ID);
        List<SysJobDto> userGwList = ycSysUserMapper.getUserGwByUserId(userGw, userId);
        if (CollectionUtil.isEmpty(userGwList)){
            ycSysUserMapper.addSysUserGw(GetUuIdUtils.ReplaceUuId(),userId,SpcyCommonConstant.JCY_GW_ID);
        }*/
        sysUserService.genJcyUserJobGx(userId);

        return CollectionUtil.newArrayList(msg_SFZH,msg_cjcz,msg_cjsl,msg_usercz,msg_usersl);
    }

    /**
     * 中心人员-身份证号信息同步-手机号同步
     */
    public void syncSpcyCenterUserInfo(String orgName){
        if (StringUtils.isBlank(orgName)){
            return;
        }

        List<YcSysUser> userList = sysUserService.list(new LambdaQueryWrapper<YcSysUser>()
                .eq(YcSysUser::getOrgName, orgName));

        if (CollectionUtil.isEmpty(userList)){
            return;
        }

        for (YcSysUser user : userList) {
            List<SpcyRsJcydjb> djbList = spcyJcydjbService.getJcydjbByRealname(StringPatternUtils.trimString(user.getRealname()));
            if (CollectionUtil.isNotEmpty(djbList) && djbList.size() == 1){
                SpcyRsJcydjb jcydjb = djbList.get(0);

                user.setPhone(jcydjb.getPhone());
                user.setEmail(jcydjb.getEmail());
                user.setBirthday(jcydjb.getBirthday());
                user.setFsfzh(jcydjb.getFsfzh());
                user.setFzzmm(jcydjb.getFzzmm());
                user.setFmz(jcydjb.getFmz());
                user.setSex(jcydjb.getSex());
                user.setFbyyx(jcydjb.getFbyyx());
                user.setFsxzy(jcydjb.getFsxzy());
                user.setFxl(jcydjb.getFxl());
                user.setFzc(jcydjb.getFzc());

                user.setFgzdw(jcydjb.getFdwqc());
                user.setFdwlx(jcydjb.getFdwlx());
                user.setFsftxyp(jcydjb.getFsftxyp());
                user.setFgzdwdz(jcydjb.getFdwdz());
                user.setFgzdwbm(jcydjb.getFdwbm());
                user.setFsfyjsry(jcydjb.getFsfyjs());
                user.setFssqy(jcydjb.getFssds());

                user.setFcsgz(jcydjb.getFcsgz());
                user.setUserQq(jcydjb.getFqqhm());
                user.setFcz(jcydjb.getFcz());
                user.setFzw(jcydjb.getFzw());

                user.setFgznx(jcydjb.getFdwgznx());
                user.setFcsjckssj(jcydjb.getFcsjckssj());

                sysUserService.updateById(user);
            }
        }


    }


    /**
     * 导入检查员-测试
     */
    public void impJcyFileData2(MultipartFile file, HttpServletResponse response){

        String fileName = file.getOriginalFilename();
        File fileUpload = localFileUploadUtils.uploadDempFile(file,GetUuIdUtils.ReplaceUuId()+fileName);
        ExcelReader excelReader = ExcelUtil.getReader(fileUpload,0);
        List<Map<String,Object>> excelMapList = excelReader.readAll();

        List<List<String>> resultList = new ArrayList<>();
        List<String> titleList = new ArrayList<>();
        List<String> dataList = null;


        int count = 1;
        int titleSize = 0;
//        int keyIndex = 0; // 姓名关键字下标

        for (Map.Entry<String, Object> entry : excelMapList.get(0).entrySet()) {
            String key = Optional.ofNullable(entry.getKey()).orElseGet(() -> "");
            titleList.add(key);

            /*if (StringUtils.isNotBlank(key) && key.equals("身份证")){
                keyIndex = titleSize;
            }*/

            titleSize++;
        }

        titleList.add("检查类别");
        resultList.add(titleList);


        for(Map<String,Object> excelMap : excelMapList){

            Set<Map.Entry<String, Object>> entries = excelMap.entrySet();

            if (count > 0){

                int forCount = 0;
                String keyRealname = "";
                dataList = new ArrayList<>();

                String lx = ""; // 检查员类别
                for (Map.Entry<String, Object> entry : entries) {

                    String key = Optional.ofNullable(entry.getKey()).orElseGet(() -> "");

                    String value = "";
                    if (entry.getValue() != null){
                        value = StringPatternUtils.trimString(entry.getValue().toString());
                    }
                    dataList.add(value);

                    /*if (keyIndex == forCount) {
                        keyRealname = value;
                    }*/

                    if (StringUtils.isNotBlank(key) && key.equals("身份证")){
                        keyRealname = value;
                    }

                    if (StringUtils.isNotBlank(key) && key.equals("检查类型")){
                        lx = value;
                    }

//                    forCount++;
                }

                String ssk = ""; // 所属库
                if (StringUtils.isNotBlank(keyRealname)) {
                    List<YcSysUser> userList = sysUserService.selectUserBySfzh(keyRealname);
                    if (CollectionUtil.isNotEmpty(userList)) {
                        LambdaQueryWrapper<SpcyRsHcy> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(SpcyRsHcy::getFuserid, userList.get(0).getId());
                        queryWrapper.eq(SpcyRsHcy::getFusertype, SpcyConstant.HCY_USERTYPE_JCY);
                        List<SpcyRsHcy> hcyList = spcyRsHcyService.list(queryWrapper);

                        for (int order = 0; order < hcyList.size(); order++) {
                            if (StringUtils.isNotBlank(hcyList.get(order).getFlx()) && !lx.contains(JcydjbConstant.LB_YPZCSC)){
                                lx += StringUtils.isNotBlank(lx) ? "/" + hcyList.get(order).getFlx() : hcyList.get(order).getFlx();

                                String fssk = Optional.ofNullable(hcyList.get(order).getFssk()).orElseGet(() -> "无");
                                ssk += StringUtils.isNotBlank(ssk) ? "/" + fssk : fssk;
                            }
                        }
                    }
                }

                dataList.add(lx);
                resultList.add(dataList);
            }

            count++;
        }
        excelReader.close();
        fileUpload.delete();

        // 文件名称
        String title = "数据对比";
        ExcelUtils.getLocalTitleExcel(resultList,title,response);
    }

    public void impJcyFileData3(MultipartFile file, String fxllx, String fjcylb, String fjcyxl, HttpServletResponse response){
        if (file.isEmpty()){
//            return HttpResult.error("文件不存在");
        }

        //获取文件名
        String fileName = file.getOriginalFilename();

        //判断文件类型，这里我们只要xls文件
        if (fileName != null && !fileName.endsWith(".xls") && !fileName.endsWith(".xlsx")) {
//            return HttpResult.error(1, "请选择“xls”或“xlsx”文件");
        }

        File fileUpload = localFileUploadUtils.uploadDempFile(file,fileName);

        // 获取导入的数据
        List<Map<String, Object>> mapsList = null;
        try {
            mapsList = myExcelUtils.paresExclToMapList(BusinessConstant.IMPORT_JCY_ACCOUNT_XML, fileUpload);
        } catch (Exception e) {
            log.error("导入检查员数据出错-{}",e.getMessage());
        }

        List<List<String>> msgList = new ArrayList<>();
        msgList.add(CollectionUtil.newArrayList("身份证号","采集表是否存在","采集数量","用户表存在","用户数量"));

        if (CollectionUtils.isNotEmpty(mapsList) && mapsList.size() > 0) {
            for (int order = 0; order < mapsList.size(); order++){
                ImportJcyBo importJcyBo = new ImportJcyBo();
                BeanUtil.copyProperties(mapsList.get(order),importJcyBo); // 将导入数据复制替换
                importJcyBo.setFjcylb(fjcylb);
                importJcyBo.setFxllx(fxllx);
                importJcyBo.setFjcyxl(fjcyxl);
                msgList.add(initUploadJcyDataTest2(importJcyBo, order, true));
            }
        }

        // 文件名称
        String title = "数据对比";
        ExcelUtils.getLocalTitleExcel(msgList,title,response);
    }


    /**
     * 导出检查员类别数据-表格excel-测试-药品注册生产
     */
    public void exportJcyLbDataTest(HttpServletResponse response){
        List<List<String>> resultList = new ArrayList<>();

        // 表头
        String[] titles = new String[]{"姓名","性别","手机号","工作单位","所在地市","单位类型","检查类型","备注","用户id"};
        List<String> titleList = CollectionUtil.newArrayList(titles);
        resultList.add(titleList);

        // 相关检查员信息
        List<SpcyRsHcy> jcyList = spcyRsHcyMapper.selectList(new LambdaQueryWrapper<SpcyRsHcy>()
                .eq(SpcyRsHcy::getFlx, "药品注册生产"));

        List<String> userIdList = new ArrayList<>();
        for (int order = 0; order < jcyList.size(); order++){
            // 数据

            String fuserid = jcyList.get(order).getFuserid();

            boolean isAdd = false;
            String bz = "";
            List<SpcyRsHcy> jcy2List = spcyRsHcyMapper.selectList(new LambdaQueryWrapper<SpcyRsHcy>()
                    .eq(SpcyRsHcy::getFlx, "药品注册生产")
                    .eq(SpcyRsHcy::getFuserid, fuserid));
            if (jcy2List.size() == 1){
                if (jcy2List.get(0).getFssk().equals("预备检查员")){
                    isAdd = true;
                    bz = jcy2List.get(0).getFjcyxl();
                }
            }else if (jcy2List.size() > 1){
                String fssk1 = jcy2List.get(0).getFssk();
                String fssk2 = jcy2List.get(1).getFssk();

                if (fssk1.equals("预备检查员") && fssk2.equals("预备检查员")){
                    isAdd = true;
                    bz = "药品注册生产";
                }

            }

            if (isAdd){
                if (userIdList.contains(fuserid)){
                    continue;
                }

                userIdList.add(fuserid);
                List<String> dataList = new ArrayList<>();
                YcSysUser user = sysUserService.getById(fuserid);

                dataList.add(user.getRealname());

                String xb = "";
                if (user.getSex() == null){
                    xb = "";
                }else if (user.getSex() == 1){
                    xb = "男";
                }else if (user.getSex() == 2){
                    xb = "女";
                }
                dataList.add(xb);
                dataList.add(user.getPhone());
                dataList.add(user.getFgzdw());

                dataList.add(user.getFssqy());
                dataList.add(user.getFdwlx());
                dataList.add("药品注册生产");
                dataList.add(bz);
                dataList.add(fuserid);

                resultList.add(dataList);
            }
        }

        // 文件名称
        String title = "检查员信息"+"("+ DateConversionUtils.DateToYear(new Date())+")";

        String rootUrl = localFileUploadUtils.getTempFileRootUrl();

        File outFile = ExcelUtils.getLocalDempXlsExcel(resultList, title, rootUrl);

        localFileUploadUtils.ejzLocalFileByZdyFile(outFile,response);
    }

    /**
     * 导出检查员账户数据-表格excel-不包含预备检查员
     */
    public void exportJcyLbDataTest2(YcSysUser user, List<YcSysUser> userList, HttpServletResponse response){
        List<List<String>> resultList = new ArrayList<>();

        // 表头
        String[] titles = new String[]{"序号","身份证号","姓名","性别","手机号","工作单位","单位类型","所在地市","检查类型"};
        List<String> titleList = CollectionUtil.newArrayList(titles);
        resultList.add(titleList);

        if (CollectionUtil.isEmpty(userList)) {
            userList = spcyRsHcyMapper.selectJcyUserList(user);
        }

        for (int i=0; i<userList.size(); i++){
            LambdaQueryWrapper<SpcyRsHcy> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SpcyRsHcy::getFuserid, userList.get(i).getId());
            queryWrapper.ne(SpcyRsHcy::getFssk, SpcyConstant.HCY_SSK_YB);
            queryWrapper.last("order by instr ('药品注册生产,药物临床,药品流通,医疗器械生产流通,医疗器械临床,化妆品生产', flx)");
            List<SpcyRsHcy> hcyList = spcyRsHcyService.list(queryWrapper);

            String lx = ""; // 检查员类别
            for (int order=0; order<hcyList.size(); order++){
                if (StringUtils.isNotBlank(hcyList.get(order).getFlx())
                        && StringUtils.isNotBlank(lx)
                        && hcyList.get(order).getFlx().equals(JcydjbConstant.LB_YPZCSC)
                        && lx.contains(JcydjbConstant.LB_YPZCSC)) {
                }else {
                    String flx = hcyList.get(order).getFlx();
                    if (flx.equals(JcydjbConstant.LB_YPZCSC)){
                        lx += StringUtils.isNotBlank(lx) ? "/" + flx : flx;

                    }else if (flx.equals(JcydjbConstant.LB_YPLC)){
                        lx += StringUtils.isNotBlank(lx) ? "/" + flx : flx;

                    }else if (flx.equals(JcydjbConstant.LB_YPLT)){
                        lx += StringUtils.isNotBlank(lx) ? "/" + flx : flx;

                    }else if (flx.equals(JcydjbConstant.LB_YLQXSCLT)){
                        lx += StringUtils.isNotBlank(lx) ? "/" + flx : flx;

                    }else if (flx.equals(JcydjbConstant.LB_YLQXLC)){
                        lx += StringUtils.isNotBlank(lx) ? "/" + flx : flx;

                    }else if (flx.equals(JcydjbConstant.LB_HZPJCY)){
                        lx += StringUtils.isNotBlank(lx) ? "/" + flx : flx;
                    }
                }
            }

            // 数据
            List<String> dataList = new ArrayList<>();

            dataList.add(String.valueOf(i+1));

            dataList.add(userList.get(i).getFsfzh());
            dataList.add(userList.get(i).getRealname());
            String sex = "";
            if (userList.get(i).getSex() != null){
                if (userList.get(i).getSex().equals(1)){
                    sex = "男";
                }else if (userList.get(i).getSex().equals(2)){
                    sex = "女";
                }
            }
            dataList.add(sex);
            dataList.add(userList.get(i).getPhone());

            dataList.add(userList.get(i).getFgzdw());
            dataList.add(userList.get(i).getFdwlx());

            dataList.add(userList.get(i).getFssqy());

            dataList.add(lx);

            resultList.add(dataList);
        }

        // 文件名称
        String title = "检查员信息"+"("+ DateConversionUtils.DateToYear(new Date())+")";

        ExcelUtils.getLocalTitleExcel(resultList,title,response);
    }

    /**
     * 数据对比-导出对应信息-正式检查员
     * @param file
     * @param response
     */
    public void dataComparisonExportZsJcyInfo(MultipartFile file, HttpServletResponse response){
        String fileName = file.getOriginalFilename();
        File fileUpload = localFileUploadUtils.uploadDempFile(file,GetUuIdUtils.ReplaceUuId()+fileName);
        ExcelReader excelReader = ExcelUtil.getReader(fileUpload,0);
        List<Map<String,Object>> excelMapList = excelReader.readAll();

        List<List<String>> resultList = new ArrayList<>();
        List<String> titleList = new ArrayList<>();
        List<String> dataList = null;


        int count = 1;
        int titleSize = 0;
        int keyIndex = 0; // 姓名关键字下标
        int gzdwIndex = 0; // 工作单位下标

        for (Map.Entry<String, Object> entry : excelMapList.get(0).entrySet()) {
            String key = Optional.ofNullable(entry.getKey()).orElseGet(() -> "");
            titleList.add(key);

            if (StringUtils.isNotBlank(key) && key.equals("姓名")){
                keyIndex = titleSize;
            }

            if (StringUtils.isNotBlank(key) && key.equals("工作单位")){
                gzdwIndex = titleSize;
            }

            titleSize++;
        }

        titleList.add("是否存在库");
        titleList.add("是否重名");
        titleList.add("库检查类型");

        resultList.add(titleList);


        for(Map<String,Object> excelMap : excelMapList){

            Set<Map.Entry<String, Object>> entries = excelMap.entrySet();

            if (count > 0){

                int forCount = 0;
                String keyRealname = "";
                String keyGzdw = "";

                dataList = new ArrayList<>();

                for (Map.Entry<String, Object> entry : entries) {

                    String value = "";
                    if (entry.getValue() != null){
                        value = StringPatternUtils.trimString(entry.getValue().toString());
                    }
                    dataList.add(value);

                    if (keyIndex == forCount) {
                        keyRealname = value;
                    }

                    if (gzdwIndex == forCount) {
                        keyGzdw = value;
                    }

                    forCount++;
                }


                String sfczk = "否"; // 是否存在库
                String sfcm = "否"; // 是否重名
                String lx = ""; // 库检查类型

                if (StringUtils.isNotBlank(keyRealname)) {
                    List<YcSysUser> userList = sysUserService.list(new LambdaQueryWrapper<YcSysUser>()
                            .eq(YcSysUser::getRealname, keyRealname));
                    if (CollectionUtil.isNotEmpty(userList)){
                        String nowUserId = "";
                        sfczk = "是";

                        if (userList.size() > 1){
                            sfcm = "是";

                            if (StringUtils.isNotBlank(keyGzdw)) {
                                for (int i = 0; i < userList.size(); i++) {

                                    if (StringUtils.isNotBlank(nowUserId)){
                                        break;
                                    }

                                    if (StringUtils.isNotBlank(userList.get(i).getFgzdw())
                                            && userList.get(i).getFgzdw().equals(keyGzdw)){
                                        nowUserId = userList.get(i).getId();
                                    }
                                }
                            }
                        }else if (userList.size() == 1){
                            nowUserId = userList.get(0).getId();
                        }


                        if (StringUtils.isNotBlank(nowUserId)) {
                            LambdaQueryWrapper<SpcyRsHcy> queryWrapper = new LambdaQueryWrapper<>();
                            queryWrapper.eq(SpcyRsHcy::getFuserid, nowUserId);
                            queryWrapper.ne(SpcyRsHcy::getFssk, SpcyConstant.HCY_SSK_YB);
                            queryWrapper.last("order by instr ('药品注册生产,药物临床,药品流通,医疗器械生产流通,医疗器械临床,化妆品生产', flx)");
                            List<SpcyRsHcy> hcyList = spcyRsHcyService.list(queryWrapper);

                            for (int order = 0; order < hcyList.size(); order++) {
                                if (StringUtils.isNotBlank(hcyList.get(order).getFlx())
                                        && StringUtils.isNotBlank(lx)
                                        && hcyList.get(order).getFlx().equals(JcydjbConstant.LB_YPZCSC)
                                        && lx.contains(JcydjbConstant.LB_YPZCSC)) {
                                } else {
                                    String flx = hcyList.get(order).getFlx();
                                    if (flx.equals(JcydjbConstant.LB_YPZCSC)) {
                                        lx += StringUtils.isNotBlank(lx) ? "/" + flx : flx;

                                    } else if (flx.equals(JcydjbConstant.LB_YPLC)) {
                                        lx += StringUtils.isNotBlank(lx) ? "/" + flx : flx;

                                    } else if (flx.equals(JcydjbConstant.LB_YPLT)) {
                                        lx += StringUtils.isNotBlank(lx) ? "/" + flx : flx;

                                    } else if (flx.equals(JcydjbConstant.LB_YLQXSCLT)) {
                                        lx += StringUtils.isNotBlank(lx) ? "/" + flx : flx;

                                    } else if (flx.equals(JcydjbConstant.LB_YLQXLC)) {
                                        lx += StringUtils.isNotBlank(lx) ? "/" + flx : flx;

                                    } else if (flx.equals(JcydjbConstant.LB_HZPJCY)) {
                                        lx += StringUtils.isNotBlank(lx) ? "/" + flx : flx;
                                    }
                                }
                            }
                        }

                    }
                }

                dataList.add(sfczk);
                dataList.add(sfcm);
                dataList.add(lx);

                resultList.add(dataList);
            }

            count++;
        }
        excelReader.close();
        fileUpload.delete();

        // 文件名称
        String title = "数据对比";
        ExcelUtils.getLocalTitleExcel(resultList,title,response);
    }

    /**
     * 数据对比-导出对应信息-正式检查员
     * @param file
     * @param response
     */
    public void dataComparisonPhoneExportZsJcyInfo(MultipartFile file, HttpServletResponse response){
        String fileName = file.getOriginalFilename();
        File fileUpload = localFileUploadUtils.uploadDempFile(file,GetUuIdUtils.ReplaceUuId()+fileName);
        ExcelReader excelReader = ExcelUtil.getReader(fileUpload,0);
        List<Map<String,Object>> excelMapList = excelReader.readAll();

        List<List<String>> resultList = new ArrayList<>();
        List<String> titleList = new ArrayList<>();
        List<String> dataList = null;


        int count = 1;
        int titleSize = 0;
        int keyIndex = 0; // 姓名关键字下标
        int gzdwIndex = 0; // 工作单位下标
        int phoneIndex = 0; // 手机号下标

        for (Map.Entry<String, Object> entry : excelMapList.get(0).entrySet()) {
            String key = Optional.ofNullable(entry.getKey()).orElseGet(() -> "");
            titleList.add(key);

            if (StringUtils.isNotBlank(key) && key.equals("姓名")){
                keyIndex = titleSize;
            }

            if (StringUtils.isNotBlank(key) && key.equals("工作单位")){
                gzdwIndex = titleSize;
            }

            if (StringUtils.isNotBlank(key) && key.equals("手机号码")){
                phoneIndex = titleSize;
            }

            titleSize++;
        }

        titleList.add("是否存在库");
        titleList.add("是否重名");
        titleList.add("手机号匹配数");
        titleList.add("库检查类型");

        resultList.add(titleList);


        for(Map<String,Object> excelMap : excelMapList){

            Set<Map.Entry<String, Object>> entries = excelMap.entrySet();

            if (count > 0){

                int forCount = 0;
                String keyRealname = "";
                String keyGzdw = "";
                String keyPhone = "";

                dataList = new ArrayList<>();

                for (Map.Entry<String, Object> entry : entries) {

                    String value = "";
                    if (entry.getValue() != null){
                        value = StringPatternUtils.trimString(entry.getValue().toString());
                    }
                    dataList.add(value);

                    if (keyIndex == forCount) {
                        keyRealname = value;
                    }

                    if (gzdwIndex == forCount) {
                        keyGzdw = value;
                    }

                    if (phoneIndex == forCount) {
                        keyPhone = value;
                    }

                    forCount++;
                }


                String sfczk = "否"; // 是否存在库
                String sfcm = "否"; // 是否重名
                String lx = ""; // 库检查类型
                int phoneFlag = 0; // 手机号查询数量
                String nowUserId = "";

                if (StringUtils.isNotBlank(keyPhone)){
                    List<YcSysUser> userList = sysUserService.list(new LambdaQueryWrapper<YcSysUser>()
                            .eq(YcSysUser::getPhone, keyPhone));
                    if (CollectionUtil.isNotEmpty(userList)){
                        if (userList.size() == 1){
                            nowUserId = userList.get(0).getId();
                        }
                    }

                    phoneFlag = userList.size();
                }

                if (StringUtils.isNotBlank(keyRealname) && phoneFlag == 0) {
                    List<YcSysUser> userList = sysUserService.list(new LambdaQueryWrapper<YcSysUser>()
                            .eq(YcSysUser::getRealname, keyRealname));
                    if (CollectionUtil.isNotEmpty(userList)){
                        sfczk = "是";

                        if (userList.size() > 1){
                            sfcm = "是";

                            if (StringUtils.isNotBlank(keyGzdw)) {
                                for (int i = 0; i < userList.size(); i++) {

                                    if (StringUtils.isNotBlank(nowUserId)){
                                        break;
                                    }

                                    if (StringUtils.isNotBlank(userList.get(i).getFgzdw())
                                            && userList.get(i).getFgzdw().equals(keyGzdw)){
                                        nowUserId = userList.get(i).getId();
                                    }
                                }
                            }
                        }else if (userList.size() == 1){
                            nowUserId = userList.get(0).getId();
                        }
                    }
                }

                if (StringUtils.isNotBlank(nowUserId)) {
                    LambdaQueryWrapper<SpcyRsHcy> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(SpcyRsHcy::getFuserid, nowUserId);
                    queryWrapper.ne(SpcyRsHcy::getFssk, SpcyConstant.HCY_SSK_YB);
                    queryWrapper.last("order by instr ('药品注册生产,药物临床,药品流通,医疗器械生产流通,医疗器械临床,化妆品生产', flx)");
                    List<SpcyRsHcy> hcyList = spcyRsHcyService.list(queryWrapper);

                    for (int order = 0; order < hcyList.size(); order++) {
                        if (StringUtils.isNotBlank(hcyList.get(order).getFlx())
                                && StringUtils.isNotBlank(lx)
                                && hcyList.get(order).getFlx().equals(JcydjbConstant.LB_YPZCSC)
                                && lx.contains(JcydjbConstant.LB_YPZCSC)) {
                        } else {
                            String flx = hcyList.get(order).getFlx();
                            if (flx.equals(JcydjbConstant.LB_YPZCSC)) {
                                lx += StringUtils.isNotBlank(lx) ? "/" + flx : flx;

                            } else if (flx.equals(JcydjbConstant.LB_YPLC)) {
                                lx += StringUtils.isNotBlank(lx) ? "/" + flx : flx;

                            } else if (flx.equals(JcydjbConstant.LB_YPLT)) {
                                lx += StringUtils.isNotBlank(lx) ? "/" + flx : flx;

                            } else if (flx.equals(JcydjbConstant.LB_YLQXSCLT)) {
                                lx += StringUtils.isNotBlank(lx) ? "/" + flx : flx;

                            } else if (flx.equals(JcydjbConstant.LB_YLQXLC)) {
                                lx += StringUtils.isNotBlank(lx) ? "/" + flx : flx;

                            } else if (flx.equals(JcydjbConstant.LB_HZPJCY)) {
                                lx += StringUtils.isNotBlank(lx) ? "/" + flx : flx;
                            }
                        }
                    }
                }

                dataList.add(sfczk);
                dataList.add(sfcm);
                dataList.add(String.valueOf(phoneFlag));
                dataList.add(lx);

                resultList.add(dataList);
            }

            count++;
        }
        excelReader.close();
        fileUpload.delete();

        // 文件名称
        String title = "数据对比";
        ExcelUtils.getLocalTitleExcel(resultList,title,response);
    }

    /**
     * 数据对比-批量设置检查员高频库
     */
    public void batchSetJcyGpkByFile(MultipartFile file, String fjcyxl, HttpServletResponse response){
        if (StringUtils.isBlank(fjcyxl)){
            return;
        }

        String fileName = file.getOriginalFilename();
        File fileUpload = localFileUploadUtils.uploadDempFile(file,GetUuIdUtils.ReplaceUuId()+fileName);
        ExcelReader excelReader = ExcelUtil.getReader(fileUpload,0);
        List<Map<String,Object>> excelMapList = excelReader.readAll();

        List<List<String>> resultList = new ArrayList<>();
        List<String> titleList = new ArrayList<>();
        List<String> dataList = null;


        int count = 1;
        int titleSize = 0;
        int keyIndex = 0; // 姓名关键字下标
        int phoneIndex = 0; // 手机号下标

        for (Map.Entry<String, Object> entry : excelMapList.get(0).entrySet()) {
            String key = Optional.ofNullable(entry.getKey()).orElseGet(() -> "");
            titleList.add(key);

            if (StringUtils.isNotBlank(key) && key.equals("姓名")){
                keyIndex = titleSize;
            }

            if (StringUtils.isNotBlank(key) && key.equals("手机号码")){
                phoneIndex = titleSize;
            }

            titleSize++;
        }

        titleList.add("是否存在库");
        titleList.add("是否手机号重复");
        titleList.add("是否存在用户");

        resultList.add(titleList);


        for(Map<String,Object> excelMap : excelMapList){

            Set<Map.Entry<String, Object>> entries = excelMap.entrySet();

            if (count > 0){

                int forCount = 0;
                String keyPhone = "";

                dataList = new ArrayList<>();

                for (Map.Entry<String, Object> entry : entries) {

                    String value = "";
                    if (entry.getValue() != null){
                        value = StringPatternUtils.trimString(entry.getValue().toString());
                    }
                    dataList.add(value);

                    if (phoneIndex == forCount) {
                        keyPhone = value;
                    }

                    forCount++;
                }


                String sfczk = "否"; // 是否存在库
                String sfcm = "否"; // 是否手机号重名
                String sfczUser = "否"; // 是否存在用户

                String nowUserId = "";

                if (StringUtils.isNotBlank(keyPhone)){
                    List<YcSysUser> userList = sysUserService.list(new LambdaQueryWrapper<YcSysUser>()
                            .eq(YcSysUser::getPhone, keyPhone));
                    if (CollectionUtil.isNotEmpty(userList)){
                        if (userList.size() == 1){
                            nowUserId = userList.get(0).getId();
                            sfczUser = "是";
                        }else {
                            sfcm = "是";
                        }
                    }
                }

                if (StringUtils.isNotBlank(nowUserId)) {

                    LambdaUpdateWrapper<SpcyRsHcy> updateWrapper = new LambdaUpdateWrapper<>();
                    updateWrapper.eq(SpcyRsHcy::getFuserid, nowUserId);
                    updateWrapper.eq(SpcyRsHcy::getFjcyxl, fjcyxl);

                    SpcyRsHcy updateBean = new SpcyRsHcy();
                    updateBean.setFgpk(SpcyConstant.JCY_GKP_YES);
                    boolean update = spcyRsHcyService.update(updateBean, updateWrapper);
                    if (update){
                        sfczk = "是";
                    }
                }

                dataList.add(sfczk);
                dataList.add(sfcm);
                dataList.add(sfczUser);

                resultList.add(dataList);
            }

            count++;
        }
        excelReader.close();
        fileUpload.delete();

        // 文件名称
        String title = "数据对比";
        ExcelUtils.getLocalTitleExcel(resultList,title,response);
    }
}
